[题目]
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.
[中文翻译]
给定一个数字字符串,返回数字可能代表的所有可能的字母组合。
下面给出了数字到字母的映射(就像电话上的按钮)。
输入: 数字字符串“23”
输出: [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].
注意:
虽然上面的答案是按字典顺序,你的答案可以是任何你想要的顺序。
[解题思路]
显然可以把映射关系存成一个二维数组,然后写个十重for循环可以解决问题。但这不是一个通用的解法。
我们需要的是一个遍历所有可能的遍历方法。实际上,就是一个计数器,在最后一位不断地加1,如果枚举完了当前位,则当前位置零,进位,进位的时候考虑连续进位的情况。每一次计数,对应一个枚举的可能,实际上这就是按字典序在枚举。这样就能实现遍历所有的可能。
[C++代码]
class Solution {
public:
vector<string> letterCombinations(string digits) {
vector<string> phoneNumberString;
vector<string> res;
phoneNumberString.push_back("");
phoneNumberString.push_back("");
phoneNumberString.push_back("abc");
phoneNumberString.push_back("def");
phoneNumberString.push_back("ghi");
phoneNumberString.push_back("jkl");
phoneNumberString.push_back("mno");
phoneNumberString.push_back("pqrs");
phoneNumberString.push_back("tuv");
phoneNumberString.push_back("wxyz");
int* index = new int[digits.size() + 1];
for (int i = 0; i < digits.size() + 1; i++)
index[i] = 0;
if (0 == digits.size())
index[0] = 1;
while (index[digits.size()] != 1) {
string addString = "";
int i;
for (i = 0; i < digits.size(); i++)
addString += phoneNumberString.at(digits.at(i) - '0').at(index[i]);
res.push_back(addString);
index[0]++;
i = 0;
while (i < digits.size() && index[i] == phoneNumberString.at(digits.at(i) - '0').size()) {
index[i] = 0;
i++;
index[i]++;
}
}
delete(index);
return res;
}
};