题目
Given a digit string, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below.
Input:Digit string "23" Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
需要建立数字与字母的对应表,顺序遍历digits,根据当前数字找到对应的字符串,然后提取字符串中的每个元素形成候选串,将候选串传入下次递归中与下一个digits中的字符串进行组合。
class Solution {
public:
void combine(string& digits,vector<string>& res,int index,string s,vector<string>& num2letter){
if(index==digits.size())//如果index遍历到digits的末尾,则形成的字符串s压入res
res.push_back(s);
string tmp=num2letter[digits[index]-'2'];//提取index数字对应的字符串
for(int i=0;i<tmp.size();++i){//对该字符串的每个元素与后面的digits进行组合
combine(digits,res,index+1,s+tmp[i],num2letter);
}
}
vector<string> letterCombinations(string digits) {
vector<string> num2letter={"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};//建立数字和字母的对应表
vector<string> res;//保存结果
int size=digits.size();
if(size==0)//检查digits是否合法
return res;
for(int i=0;i<size;++i){
if(digits[i]<'2'||digits[i]>'9')
return res;
}
combine(digits,res,0,"",num2letter);//进行组合
return res;
}
};