-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLetterCombinations.java
More file actions
54 lines (31 loc) · 1.1 KB
/
LetterCombinations.java
File metadata and controls
54 lines (31 loc) · 1.1 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
45
46
47
48
49
50
51
52
53
54
package com.vinay.practice.lc;
import java.util.ArrayList;
import java.util.List;
public class LetterCombinations {
private static String[] keypad = {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(letterCombinations("23"));
}
public static List<String> letterCombinations(String digits) {
List<String> combination = new ArrayList<>();
if(digits.isEmpty()) {
return combination;
}
getCombinations(digits, 0, new StringBuilder(), combination);
return combination;
}
// backtracking
public static void getCombinations(String digits, int index, StringBuilder sb, List<String> combination){
if(digits.length() == index) {
combination.add(sb.toString());
return;
}
int digit = digits.charAt(index) - '0'; // convert '2' to 2
for(int i=0; i<keypad[digit].length(); i++) {
sb.append(keypad[digit].charAt(i));
getCombinations(digits, index+1, sb, combination);
sb.deleteCharAt(sb.length()-1);
}
}
}