题目
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
思路一 递归+回溯
- 将数字对应的字符串,都存储在hash表中
- 第一个数字时,枚举它所有的字符
- 第二个数字,继续在第一个数字的枚举上 继续枚举,形成字符串,一直到数字遍历结束
class Solution {
public List<String> letterCombinations(String digits) {
List<String> res = new ArrayList<>();
if (digits.length() == 0) {
return res;
}
Map<Character, String> map = new HashMap<>();
map.put('2', "abc");
map.put('3', "def");
map.put('4', "ghi");
map.put('5', "jkl");
map.put('6', "mno");
map.put('7', "pqrs");
map.put('8', "tuv");
map.put('9', "wxyz");
dfs("", digits, 0 , res, map);
return res;
}
public void dfs(String s, String digits, int level, List<String> res, Map<Character, String> map) {
if (level >= digits.length()) {
res.add(s);
return;
}
String letters = map.get(digits.charAt(level)); //得到那一层数字所对应的字符串
for (int i = 0; i < letters.length(); i++) {
dfs(s + letters.charAt(i), digits, level + 1, res, map);
}
}
}
复杂度分析
时间复杂度:O(3n * 4m),n为三个字符的数字个数,m为四个字符的数字个数
空间复杂度:O(3n * 4m),输出的结果存储空间