-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path17_LetterCombinationOfPhoneNumber.java
55 lines (48 loc) · 1.79 KB
/
17_LetterCombinationOfPhoneNumber.java
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
45
46
47
48
49
50
51
52
53
54
55
// Given a digit string, return all possible letter combinations that the number could represent.
// A mapping of digit to letters (just like on the telephone buttons) is given below.
// Input:Digit string "23"
// Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
// Note:
// Although the above answer is in lexicographical order, your answer could be in any order you want.
//dfs
public class Solution {
public List<String> letterCombinations(String digits) {
String[] map = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
List<String> res = new ArrayList<String>();
if(digits.length() < 1) return res;
helper(digits, 0, res, map, "");
return res;
}
public void helper(String digits, int pos, List<String> res, String[] map, String pre) {
if(pos == digits.length()) {
res.add(pre);
return;
}
int mapPos = digits.charAt(pos) - '0';
for(Character ch : map[mapPos].toCharArray()) {
helper(digits, pos + 1, res, map, pre + ch);
}
}
}
//bt
public class Solution {
public List<String> letterCombinations(String digits) {
List<String> res = new ArrayList<>();
if(digits.length() < 1) return res;
String[] map = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
res.add("");
for(int i=0; i<digits.length(); i++) {
res = helper(res, map[digits.charAt(i) - '0']);
}
return res;
}
private List<String> helper(List<String> list, String map) {
List<String> res = new ArrayList<>();
for(int i=0; i<map.length(); i++) {
for(String s : list) {
res.add(s + map.charAt(i));
}
}
return res;
}
}