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"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
算法:DFS。函数头是private void dfs(String digits, int idx, String[] map, StringBuilder crt, List<String> result)
每次对当前这个数字可能表示的几种字母for循环去尝试。
细节:1.StringBuilder回溯的函数是sb.deleteCharAt(index)!!没有remove方法,只有delete(区间), deleteCharAt(位置)方法。 2.JAVA没有Integer.parseInt(Char)方法,可能是觉得char转int足够了就用c-'0'. 3.小心0,1的处理,不是就直接返回了,而是也要dfs下一个数字再返回。 4.出口不是看做出来的字符串的长度了,而是看现在遍历数字遍历完了没有
实现:
class Solution { public List<String> letterCombinations(String digits) { List<String> result = new ArrayList<>(); if (digits == null || digits.length() == 0) { return result; } String[] map = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; dfs(digits, 0, map, new StringBuilder(), result); return result; } private void dfs(String digits, int idx, String[] map, StringBuilder crt, List<String> result) { if (idx >= digits.length() && crt.length() > 0) { result.add(crt.toString()); return; } // Integer.parseInt居然神坑,不支持转char int digit =digits.charAt(idx) - '0'; if (digit == 0 || digit == 1) { dfs(digits, idx + 1, map, crt, result); return; } String chars = map[digit]; for (int i = 0; i < chars.length(); i++) { crt.append(chars.charAt(i)); dfs(digits, idx + 1, map, crt, result); crt.deleteCharAt(crt.length() - 1); } } }