forked from mengli/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLetter Combinations of a Phone Number.java
More file actions
33 lines (28 loc) · 1.11 KB
/
Letter Combinations of a Phone Number.java
File metadata and controls
33 lines (28 loc) · 1.11 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
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"].
public class Solution {
private char[][] map = new char[][] { { 'a', 'b', 'c' }, { 'd', 'e', 'f' },
{ 'g', 'h', 'i' }, { 'j', 'k', 'l' }, { 'm', 'n', 'o' },
{ 'p', 'q', 'r', 's' }, { 't', 'u', 'v'}, { 'w', 'x', 'y', 'z' } };
public ArrayList<String> letterCombinations(String digits) {
ArrayList<String> ret = new ArrayList<String>();
StringBuilder sb = new StringBuilder();
letterCombinations(digits, 0, sb, ret);
return ret;
}
private void letterCombinations(String digits, int i, StringBuilder sb, ArrayList<String> ret) {
if (i >= digits.length()) {
ret.add(sb.toString());
} else {
int index = digits.charAt(i) - '1' - 1;
int size = map[index].length;
for (int j = 0; j < size; j++) {
sb.append(map[index][j]);
letterCombinations(digits, i + 1, sb, ret);
sb.deleteCharAt(sb.length() - 1);
}
}
}
}