Description
Given a string containing digits from 2-9 inclusive, 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. Note that 1 does not map to any letters.
Example
Input: "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.
Solution 1(C++)
class Solution{
public:
vector<string> alpha={"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
vector<string> letterCombinations(string digits) {
vector<string> res;
if(digits.empty()) return res;
helper(res, digits, "", 0);
return res;
}
void helper(vector<string>& res, string digits, string s, int n){
if(n == digits.size()) { res.push_back(s); return; }
string temp = alpha[digits[n]-'0'];
for(int i=0; i<temp.size(); i++){
helper(res, digits, s+temp[i], n+1);
}
}
};
后续更新
其他类似的题目可参考:
算法分析
这道题难度不大,主要是要分析清楚逻辑。问题可以转换成一个比较经典的全排序的问题。使用回溯不难解决。
程序分析
略。