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
| class Solution { static String[][] dir = {{"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"}}; static List<String> result;
public static List<String> letterCombinations(String digits) { result = new ArrayList<>(); if (digits == null || digits.length() == 0) { return result; } StringBuilder builder = new StringBuilder(); dfs(digits, 0, builder); return result; }
private static void dfs(String digits, int index, StringBuilder builder) { if (builder.length() == digits.length()) { result.add(builder.toString()); return; } int i = (digits.charAt(index) - '0') - 2; String[] temp = dir[i]; for (int j = 0; j < temp.length; j++) { builder.append(temp[j]); dfs(digits, index + 1, builder); builder.deleteCharAt(builder.length() - 1); } } }
|