1.电话号码的字母组合
题目描述
给定一个仅包含数字2-9的字符串,返回所有它能表示的字母组合。答案可以按任意顺序返回。
给出数字到字母的映射如下(与电话按键相同)。注意1不对应任何字母。

题目链接
https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/
样例描述
示例一:
输入:digits = "23"
输出:["ad","ae","af","bd","be","bf","cd","ce","cf"]
示例二:
输入:digits = ""
输出:[]
示例三:
输入:digits = "2"
输出:["a","b","c"]
说明
如果输入是:
"234" abc def ghi
输出的结果是:
adg,adh,adi,aeg,aeh,aei,afg,afh,afi
bdg,bdh,bdi,beg,beh,bei,bfg,bfh,bfi
cdg,cdh,cdi,ceg,ceh,cei,cfg,cfh,cfi
复杂度分析
时间复杂度:o(3的m次方 * 4的n次方)
m是输入数字中对应有3个字母的数字个数(包括数字2,3,4,5,6,8)
n是输入数字中对应有4个字母的数字个数(包括数字7,9)
空间复杂度:O(m+n)
m是输入中对应3个字母的数字个数,
n是输入中对应4个字母的数字个数,
m+n是输入数字的总个数。
除了返回值以外,空间复杂度主要取决于哈希表以及回溯过程中的递归调用层数,哈希表的大小与输入无关,可以看成常数,递归调用层数最大为m+n。
代码
class Solution {
public List<String> letterCombinations(String digits) {
List<String> combinations = new ArrayList<>();
if (digits.length() == 0) {
return combinations;
}
Map<Character, String> phoneMap = new HashMap<>();
phoneMap.put('2', "abc");
phoneMap.put('3', "def");
phoneMap.put('4', "ghi");
phoneMap.put('5', "jkl");
phoneMap.put('6', "mno");
phoneMap.put('7', "pqrs");
phoneMap.put('8', "tuv");
phoneMap.put('9', "wxyz");
backtrack(combinations, phoneMap, digits, 0, new StringBuffer());
return combinations;
}
public void backtrack(List<String> combinations, Map<Character, String> phoneMap, String digits, int index, StringBuffer combination) {
if (digits.length() == index) {
combinations.add(combination.toString());
} else {
char digit = digits.charAt(index);
String letters = phoneMap.get(digit);
int lettersCount = letters.length();
for (int i = 0; i < lettersCount; i++) {
combination.append(letters.charAt(i));
backtrack(combinations, phoneMap, digits, index+1, combination);
combination.deleteCharAt(index);
}
}
}
}
本文来自博客园,作者:jsqup,转载请注明原文链接:https://www.cnblogs.com/jsqup/p/15836279.html

浙公网安备 33010602011771号