给一个不包含’0’和’1’的数字字符串,每个数字代表一个字母,请返回其所有可能的字母组合。
下图的手机按键图,就表示了每个数字可以代表的字母。
1 | 2 | 3 |
---|---|---|
abc | def | |
4 | 5 | 6 |
ghi | jkl | mno |
7 | 8 | 9 |
pqrs | tuv | wxyz |
样例
样例 1:
输入: "23"
输出: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]
解释:
'2' 可以是 'a', 'b' 或 'c'
'3' 可以是 'd', 'e' 或 'f'
样例 2:
输入: "5"
输出: ["j", "k", "l"]
注意事项
以上的答案是按照词典编撰顺序进行输出的,不过,在做本题时,你也可以任意选择你喜欢的输出顺序。
class Solution {
public:
/**
* @param digits: A digital string
* @return: all posible letter combinations
*/
vector letterCombinations(string &digits) {
// write your code here
vector word={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
vectorres;
if(digits.size()<=0) return res;
dfs(digits,res,0,"",word);
return res;
}
void dfs(string &digits,vector &res,int index,string tmp,vector word)
{
if(index==digits.size())
{
res.push_back(tmp);
return ;
}
int num=digits[index]-'0';
for (int i = 0; i < word[num].size(); i++) {
tmp+=word[num][i];
dfs(digits,res,index+1,tmp,word);
tmp.erase(tmp.end()-1);
}
}
};