题目描述
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
解析
广度优先遍历或者深度优先遍历两种方式,广度优先类似构造一颗树形结构,子树就是当前节点加下一层数字对应的字母。
public List<String> letterCombinations(String digits) {List<String> res = new ArrayList<>();if (digits == null || digits.length() == 0) {return res;}Map<Character, String> phoneMap = new HashMap<Character, String>() {{put('2', "abc");put('3', "def");put('4', "ghi");put('5', "jkl");put('6', "mno");put('7', "pqrs");put('8', "tuv");put('9', "wxyz");}};Queue<String> queue = new ArrayDeque<>();queue.offer("");for (int i = 0; i < digits.length(); i++) {char curDigit = digits.charAt(i);String curString = phoneMap.get(curDigit);int size = queue.size();for (int j = 0; j < size; j++) {String parentStr = queue.poll();for (int k = 0; k < curString.length(); k++) {queue.offer(parentStr + curString.charAt(k));}}}while (!queue.isEmpty()) {res.add(queue.poll());}return res;}
深度优先遍历利用递归操作,使用一个变量去记录当前字符串的长度,达到长度后则放入结果数组中,使用字符数组可以直接覆盖回溯。
public static List<String> letterCombinations(String digits) {List<String> res = new ArrayList<>();if (digits == null || digits.length() == 0) {return res;}Map<Character, String> phoneMap = new HashMap<Character, String>() {{put('2', "abc");put('3', "def");put('4', "ghi");put('5', "jkl");put('6', "mno");put('7', "pqrs");put('8', "tuv");put('9', "wxyz");}};char[] current = new char[digits.length()];backtrack(res, phoneMap, digits, 0, current);return res;}private static void backtrack(List<String> res, Map<Character, String> phoneMap, String digits, int index, char[] current) {if (index == digits.length()) {res.add(new String(current));return;}char digit = digits.charAt(index);String letters = phoneMap.get(digit);for (int i = 0; i < letters.length(); i++) {current[index] = letters.charAt(i);backtrack(res, phoneMap, digits, index + 1, current);}}