题目描述:
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例 1:
输入:digits = “23”
输出:[“ad”,“ae”,“af”,“bd”,“be”,“bf”,“cd”,“ce”,“cf”]
示例2:
输入:digits = “”
输出:[]
示例3:
输入:digits = “”
输出:[]
提示:
0 <= digits.length <= 4
digits[i] 是范围 [‘2’, ‘9’] 的一个数字。
c++代码:
class Solution {
public:
string tmp;//tmp为当前正在构成的字符串(一个可能的字母组合)
vector<string> v;
void DFS(int pos,string digits,int n,vector<string> words){
if(pos==n){ //构成的字符串长度已经够了
v.push_back(tmp); //记录tmp
return;//返回
}
int num=digits[pos]-'0';//当前第pos位置,查找数字对应的字母
for(int i=0;i<words[num].length();i++){ //电话上数字对应的字母个数
tmp.push_back(words[num][i]); //tmp后面加入这个字母
DFS(pos+1,digits,n,words); //继续对下一个位置进行构成
tmp.pop_back(); //该字母处理完了,把该字母pop掉,继续push下一个字母
}
}
vector<string> letterCombinations(string digits) {
if(digits=="")return v;
vector<string> words= {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};//0,1不对应字母,设为空,注意是{}不是[]
int n=digits.length();
DFS(0,digits,n,words);
return v;
}
};
典型的多层查找问题,使用深度优先搜索。对于字母chr开头的可能组合,先深度优先找出所有可能的组合结果,再对一个字母chr2开头的可能组合进行搜索。
digits的长度为n,则可能组成的字母组合的长度为n,每一位从digits[i]-‘0’对应的字母中取出进行排列组合。
string tmp用来记录当前找到的可能组合,pos记录当前已经构成的组合的长度,也就是digits当前正在查找的位数。当pos=n时则表示已经找到一个组合,把它保存下来,返回;否则继续查找:把digits[pos]保存如tmp,并对pos+1继续该操作。
python代码:
class Solution(object):
def letterCombinations(self, digits):
tmp=""
res=[]
words = ["","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"]
n = len(digits)
if n==0:
return res
def DFS(pos,digits,n,words,tmp):
if pos==n:
res.append(tmp)
return
num = ord(digits[pos]) - ord('0')
for i in range(0,len(words[num])):
tmp+=words[num][i]
DFS(pos+1,digits,n,words,tmp)
tmp=tmp[0:len(tmp)-1]
DFS(0,digits,n,words,tmp)
return res
同理c++的代码,执行DFS深度优先搜索。
不过注意:
①需要在类的子函数中执行函数DFS(),函数DFS()需要写在子函数内部,定义后直接调用。
②另外不便于在类中先定义全局变量,再在函数DFS()中修改,所以直接把tmp变量传入DFS()中。
总结:
1.c++中的动态数组vector<>声明用大括号{}。
2.python中的列表用小括号()。
3.python子函数中想调用函数,直接在子函数中声明函数再调用。