-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathLetterCombinationsOfAPhoneNumber.java
More file actions
44 lines (39 loc) · 1.41 KB
/
LetterCombinationsOfAPhoneNumber.java
File metadata and controls
44 lines (39 loc) · 1.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/**
* LeetCode 17 https://leetcode.com/problems/letter-combinations-of-a-phone-number/
*/
class Solution {
List<String> lists = new LinkedList<>();
StringBuilder temp = new StringBuilder();
public List<String> letterCombinations(String digits) {
if (digits == null || digits.length() == 0) {
return lists;
}
String[] numToLetter = {
"", // 0
"", // 1
"abc", // 2
"def", // 3
"ghi", // 4
"jkl", // 5
"mno", // 6
"pqrs", // 7
"tuv",// 8
"wxyz" // 9
};
backtrack(digits, numToLetter, 0);
return lists;
}
void backtrack(String digits, String[] numToLetter, int index) {
// base case
if (temp.length() == digits.length()) {
lists.add(temp.toString());
return;
}
String letters = numToLetter[digits.charAt(index) - '0'];
for (int i = 0; i < letters.length(); i++ ) {
temp.append(letters.charAt(i));
backtrack(digits, numToLetter, index + 1);
temp.deleteCharAt(temp.length() - 1);
}
}
}