17. 电话号码的字母组合(中等)
给定一个仅包含数字 2-9
的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例 1:
输入:digits = "23"
输出:["ad","ae","af","bd","be","bf","cd","ce","cf"]
示例 2:
输入:digits = ""
输出:[]
示例 3:
输入:digits = "2"
输出:["a","b","c"]
思路:
- 递归:每次增加所digits[i]所对应的数字的可选字符中的一个加入temp中,通过递归,可得到最终结果。、
- 迭代法:依次根据digits字符串的数字顺序从左到右遍历的顺序往⾥⾯添加字母,每一次都追加在原有res的后面,因为res会改变所以每次设立一个空string数组temp,然后temp根据result中原有的结果向后面继续添加拼接原+新的字符串,然后res = temp进行复制
int('6')
的结果为字符6所对应的ASCII码,所想使其结果为6,应为int('6')-int('0')
,或者采用哈希表来表示d,则无需转换。- 当字符为7或9时所对应的可选字符有4个
(1)C++——递归
class Solution {
public:
vector<string> letterCombinations(string digits) {
vector<string> res;
int n = digits.length();
if(n==0) return res;
vector<string> d {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
string temp="";
help(digits,n,d,res,temp,0,0);
help(digits,n,d,res,temp,0,1);
help(digits,n,d,res,temp,0,2);
if(digits[0]=='7' || digits[0]=='9')
help(digits,n,d,res,temp,0,3);
return res;
}
int help(string& digits,int n,vector<string>& d,vector<string>& res,string temp,int i,int j){
temp += d[int(digits[i]-'0')][j];
if(i==n-1){
res.emplace_back(temp);
return 0;
}
help(digits,n,d,res,temp,i+1,0);
help(digits,n,d,res,temp,i+1,1);
help(digits,n,d,res,temp,i+1,2);
if(digits[i+1]=='7' || digits[i+1]=='9')
help(digits,n,d,res,temp,i+1,3);
return 0;
}
};
(2)C+±-迭代法
class Solution {
public:
vector<string> letterCombinations(string digits) {
vector<string> res;
if(digits.length() == 0) return res;
res.push_back("");
vector<string> v = {"", "", "abc", "def", "ghi", "jkl", "mno","pqrs", "tuv", "wxyz"};
for(int i = 0; i < digits.size(); i++) {
string s = v[digits[i] - '0'];
vector<string> temp;
for(int j = 0; j < s.length(); j++)
for(int k = 0; k < res.size(); k++)
temp.push_back(res[k] + s[j]);
res = temp;
}
return res;
}
};
(3)python–递归
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
n = len(digits)
if n==0:
return []
d = {}
d['2']='abc'
d['3']='def'
d['4']='ghi'
d['5']='jkl'
d['6']='mno'
d['7']='pqrs'
d['8']='tuv'
d['9']='wxyz'
res = []
temp = ''
self.diedai(digits,n,d,temp,res,0,0)
self.diedai(digits,n,d,temp,res,0,1)
self.diedai(digits,n,d,temp,res,0,2)
if(digits[0] in '79'):
self.diedai(digits,n,d,temp,res,0,3)
return res
def diedai(self,digits,n,d,temp,res,i,j):
temp += d[digits[i]][j]
if i==n-1:
res.append(temp)
return
self.diedai(digits,n,d,temp,res,i+1,0)
self.diedai(digits,n,d,temp,res,i+1,1)
self.diedai(digits,n,d,temp,res,i+1,2)
if(digits[i+1] in '79'):
self.diedai(digits,n,d,temp,res,i+1,3)
(4)python-迭代
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
n = len(digits)
if n==0:
return []
d = ["", "", "abc", "def", "ghi", "jkl", "mno","pqrs", "tuv", "wxyz"]
res = ['']
for each in digits:
temp=[]
for a in d[int(each)-int('0')]:
for it in res:
it+=a
temp.append(it)
res = temp
return res