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.
题意:让我们求电话号码的字母组合,即数字2到9中每个数字可以代表若干个字母,然后给一串数字,求出所有可能的组合。
【迭代】
枚举所有情况。
对于每一个输入数字,对于已有的排列中每一个字符串,分别加入该数字所代表的每一个字符。
所有是三重for循环。
举例:
初始化排列{“”}
1、输入2,代表”abc”
已有排列中只有字符串“”,所以得到{“a”,”b”,”c”}
2、输入3,代表”def”
(1)对于排列中的首元素”a”,删除”a”,并分别加入’d’,’e’,’f’,得到{“b”,”c”,”ad”,”ae”,”af”}
(2)对于排列中的首元素”b”,删除”b”,并分别加入’d’,’e’,’f’,得到{“c”,”ad”,”ae”,”af”,”bd”,”be”,”bf”}
(2)对于排列中的首元素”c”,删除”c”,并分别加入’d’,’e’,’f’,得到{“ad”,”ae”,”af”,”bd”,”be”,”bf”,”cd”,”ce”,”cf”}
注意
(1)每次添加新字母时,应该先取出现有ret当前的size(),而不是每次都在循环中调用ret.size(),因为ret.size()是不断增长的。
(2)删除vector首元素代码为:
ans.erase(ans.begin());
代码:
class Solution {
public:
vector<string> letterCombinations(string digits) {
vector<string>ans;
if(!digits.size())return ans;
string a[10];
int i,j,k;
a[2]="abc";
a[3]="def";
a[4]="ghi";
a[5]="jkl";
a[6]="mno";
a[7]="pqrs";
a[8]="tuv";
a[9]="wxyz";
ans.push_back("");
for(i=0;i<digits.size();i++)
{
string temp1=a[digits[i]-'0'];
int size=ans.size();
for(j=0;j<size;j++)
{
string temp=ans[0];
ans.erase(ans.begin());
for(k=0;k<temp1.size();k++)
{
ans.push_back(temp+temp1[k]);
}
}
}
return ans;
}
};
【递归(深搜)】
class Solution {
public:
vector<string> letterCombinations(string digits) {
vector<string> res;
if (digits.empty()) return res;
string dict[] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
letterCombinationsDFS(digits, dict, 0, "", res);
return res;
}
void letterCombinationsDFS(string digits, string dict[], int level, string out, vector<string> &res) {
if (level == digits.size()) res.push_back(out);
else {
string str = dict[digits[level] - '2'];
for (int i = 0; i < str.size(); ++i) {
out.push_back(str[i]);
letterCombinationsDFS(digits, dict, level + 1, out, res);
out.pop_back();
}
}
}
};