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.
这个第一反应就是树形结构。但直接用树形结构实现比较复杂,可以使用迭代以及递归的方法。
思路一:通过迭代来实现。
代码如下:
class Solution {
public:
vector<string> letterCombinations(string digits) {
vector<string> result;
static const vector<string> v = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
if(digits.size() < 1)
return result;
result.push_back("");
for(int i=0;i<digits.length();i++)
{
vector<string> tmp;
int num = digits[i]-'0';
if(num < 0 || num > 9)
break;
if(num == 0 || num == 1)
continue;
for(int j=0;j<v[num].length();j++)
for(int k=0;k<result.size();k++)
tmp.push_back(result[k]+v[num][j]);
result = tmp;
}
return result;
}
};