Skip to content

Commit 92b5867

Browse files
authored
Backtracking
1 parent ddc3a8e commit 92b5867

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
class Solution {
2+
HashMap<Character,String>hm;
3+
List<String>ans;
4+
public List<String> letterCombinations(String digits) {
5+
ans=new ArrayList<>();
6+
if(digits==null|| digits.length()==0){
7+
return ans;
8+
}
9+
//initalize map and mapped the char and connected string
10+
hm = new HashMap<>();
11+
hm.put('2',"abc");
12+
hm.put('3',"def");
13+
hm.put('4',"ghi");
14+
hm.put('5',"jkl");
15+
hm.put('6',"mno");
16+
hm.put('7',"pqrs");
17+
hm.put('8',"tuv");
18+
hm.put('9',"wxyz");
19+
solve(digits,0,new StringBuilder());
20+
return ans;
21+
22+
}
23+
24+
private void solve(String digits,int index,StringBuilder sb){
25+
if(index>=digits.length()){
26+
ans.add(sb.toString());
27+
return ;
28+
}
29+
String connectedLetters = hm.get(digits.charAt(index));
30+
for(int i=0;i<connectedLetters.length();i++){
31+
char ch = connectedLetters.charAt(i);
32+
//add this to our temp ans -sb
33+
sb.append(ch);
34+
//traverse for the next char of index
35+
solve(digits,index+1,sb);
36+
//now remove the appended char from sb
37+
sb.deleteCharAt(sb.length()-1);
38+
}
39+
}
40+
}

0 commit comments

Comments
 (0)