-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLetterCombinations.java
More file actions
40 lines (35 loc) · 1003 Bytes
/
LetterCombinations.java
File metadata and controls
40 lines (35 loc) · 1003 Bytes
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
package Recursion;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/*
17. Letter Combinations of a Phone Number
*/
public class LetterCombinations {
Map<Character,String> numMap = Map.of(
'2', "abc",
'3', "def",
'4', "ghi",
'5', "jkl",
'6', "mno",
'7', "pqrs",
'8', "tuv",
'9', "wxyz"
);
public List<String> letterCombinations(String digits) {
List<String> res = new ArrayList<>();
if(digits.length()==0) return res;
backtrack(digits,res,0,"");
return res;
}
public void backtrack(String digits, List<String> res, int index,String cur){
if(cur.length()==digits.length()){
res.add(cur);
return;
}
String digitToChar = numMap.get(digits.charAt(index));
for( Character c: digitToChar.toCharArray()){
backtrack(digits,res,index+1,cur+c);
}
}
}