Given a string containing only numbers 2-9, return all letter combinations it can represent.
The mapping of numbers to letters is given as follows (same as phone buttons). Note that 1 does not correspond to any letters.
Example:
Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
Explanation:
Despite the above The answers are arranged in lexicographic order, but you can choose the order in which the answers are output.
Source: LeetCode (LeetCode)
link
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
Code:
class Solution {
public:
string t,s[8]={
"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
//只有2-9按键有字母
vector<string> ans;
void dfs(string digits,int index)
{
if(index==digits.size()) //下标到了digits长度,算一个组合
{
ans.push_back(t); //加入ans数组
return;
}
//digits[index]-'0'-2 找到按键可以敲出的字符
for(int i=0;i<s[digits[index]-'0'-2].size();i++) //
{
t+=s[digits[index]-'0'-2][i]; //累加字符
dfs(digits,index+1); //下标加一
t.erase(t.end()-1); //减去最后一个字符
}
}
vector<string> letterCombinations(string digits) {
if(!digits.size()) return ans; //空字符
dfs(digits,0);
return ans;
}
};