给定一个仅包含数字2-9的字符串,返回所有它能表示的字母组合。答案可以按任意顺序返回。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例 1:
输入:digits = "23"输出:["ad","ae","af","bd","be","bf","cd","ce","cf"]
关键点:
定义字符和字母的映射 '2' -> "abc"
用stringBuilder拼接递归中字母
递归中对每个按键可取字母进行遍历(穷举的过程),遍历一轮要把上轮已拼接好的删除掉,穷举拼接上新的字符
中止条件就是当前索引 == 字符串的长度
public List<String> letterCombinations(String digits) { List<String> combinations = new ArrayList<>(); if (digits.length() == 0) { return combinations; } // 初始化map Map<Character, String> photoMap = 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"); }}; letterCombinationsDfs(digits, 0, new StringBuilder(), combinations, photoMap); return combinations; } public void letterCombinationsDfs(String digits, int index, StringBuilder combination, List<String> combinations, Map<Character, String> photoMap) { if (index == digits.length()) { combinations.add(combination.toString()); } else { char digit = digits.charAt(index); String letters = photoMap.get(digit); int lettersCount = letters.length(); // 第一个字母开始进行递归 for (int i = 0; i < lettersCount; i++) { combination.append(letters.charAt(i)); // 每一个字母进行递归,进行下一个字母的递归 letterCombinationsDfs(digits, index + 1, combination, combinations, photoMap); // 删除当前字母 combination.deleteCharAt(index); } } }