-
Notifications
You must be signed in to change notification settings - Fork 0
/
17.letter-combinations-of-a-phone-number.java
70 lines (51 loc) · 1.93 KB
/
17.letter-combinations-of-a-phone-number.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
class Solution {
// List<String> res;
public List<String> letterCombinations(String digits) {
if(digits.length() == 0)
return new ArrayList<>();
String[] digitmapping = new String[10];
// res = new ArrayList<>();
digitmapping[2] = "abc";
digitmapping[3] = "def";
digitmapping[4] = "ghi";
digitmapping[5] = "jkl";
digitmapping[6] = "mno";
digitmapping[7] = "pqrs";
digitmapping[8] = "tuv";
digitmapping[9] = "wxyz";
List<String> res = new ArrayList<>();
int p = 0;
while(p<digitmapping[digits.charAt(0)-'0'].length())
{
res.add(""+digitmapping[digits.charAt(0)-'0'].charAt(p));
p++;
}
for(int i=1;i<digits.length();i++){
List<String> res2 = new ArrayList<>();
int val = digits.charAt(i)-'0';
String curr = digitmapping[val];
int c=0;
while(c<curr.length()){
for(int l=0;l<res.size();l++)
res2.add(res.get(l)+""+curr.charAt(c));
c++;
}
res = res2;
}
return res;
}
public void solve(String[] digitmapping, String digits, int i, int k, StringBuilder ans){
if(i == digits.length()){
// res.add((new StringBuilder(ans)).toString());
return;
}
for(int j=i;j<digits.length();j++){
int val = digits.charAt(j)-'0';
for(int p=0;p<digitmapping[val].length();p++){
ans.append(digitmapping[val].charAt(p));
solve(digitmapping, digits, j+1, p, ans);
ans.deleteCharAt(ans.length()-1);
}
}
}
}