-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLetterCombinationsPhoneNumber.java
More file actions
44 lines (38 loc) · 1.26 KB
/
LetterCombinationsPhoneNumber.java
File metadata and controls
44 lines (38 loc) · 1.26 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
package problem011_020;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class LetterCombinationsPhoneNumber {
private HashMap<Character, String> map = new HashMap<>();
private List<String> result = new ArrayList<>();
public List<String> letterCombinations(String digits) {
map.put('2', "abc");
map.put('3', "def");
map.put('4', "ghi");
map.put('5', "jkl");
map.put('6', "mno");
map.put('7', "pqrs");
map.put('8', "tuv");
map.put('9', "wxyz");
result = backtracking(digits, result);
return result;
}
private List<String> backtracking(String digits, List<String> result) {
if(digits.equals("")) {
return result;
}
List<String> temp = new ArrayList<>();
char digit = digits.charAt(0);
for (int i = 0; i < map.get(digit).length(); i++) {
if (result.isEmpty()) {
temp.add(String.valueOf(map.get(digit).charAt(i)));
} else {
for (String item: result) {
temp.add(item + map.get(digit).charAt(i));
}
}
}
result = backtracking(digits.substring(1), temp);
return result;
}
}