给定一个仅包含数字 2-9
的字符串,返回所有它能表示的字母组合。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

示例:
1 2
| 输入:"23" 输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
|
说明:
尽管上面的答案是按字典序排列的,但是你可以任意选择答案输出的顺序。
方法一:回溯
首先使用哈希表存储每个数字对应的所有可能的字母,然后进行回溯操作。
回溯过程中维护一个字符串,表示已有的字母排列。该字符串初始为空,每次取电话号码的一位数字,从哈希表中获取该数字对应的所有字母,将其中一个字母插入到已有字母的后面,然后继续处理电话号码的后一位数字,直到处理完所有数字,得到一个完整的字母排列。然后进行回退操作,遍历其余的字母排列。
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
| class Solution { public List<String> letterCombinations(String digits) { List<String> combinations = new ArrayList<>(); if(digits.length() == 0){ return combinations; }
Map<Character, String> numMap = new HashMap<>(); numMap.put('2', "abc"); numMap.put('3', "def"); numMap.put('4', "ghi"); numMap.put('5', "jkl"); numMap.put('6', "mno"); numMap.put('7', "pqrs"); numMap.put('8', "tuv"); numMap.put('9', "wxyz");
backtrack(combinations, numMap, digits, 0, new StringBuffer()); return combinations; }
public void backtrack(List<String> combinations, Map<Character, String> numMap, String digits, int index, StringBuffer combination){ if(index == digits.length()){ combinations.add(combination.toString()); }else{ char c = digits.charAt(index); String letters = numMap.get(c); for(int i = 0; i < letters.length(); i++){ combination.append(letters.charAt(i)); backtrack(combinations, numMap, digits, index + 1, combination); combination.deleteCharAt(index); } } } }
|
时间复杂度O(3^m * 4^ n),m 为对应三个字母的数字个数,n 为对应四个字母的数字个数。
空间复杂度O(m + n),m 为对应三个字母的数字个数,n 为对应四个字母的数字个数。除返回值外,空间复杂度取决于哈希表及递归调用层数,递归调用层数最多为 m + n。