LeetCode17:电话号码的字母组合

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。

给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

 

示例:

输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

这题主要采用回溯法,对输入的每个数字进行回溯,回溯到底部就把生成的字符串加入到返回值里面。

 1 class Solution {
 2 public:
 3     vector<string> ans;
 4     string gen;
 5     string dict[10] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
 6     vector<string> letterCombinations(string digits) {
 7         if(digits.empty()) return ans;
 8         gen.resize(digits.size());
 9         backtrace(digits,0);
10         return ans;
11     }
12 
13     void backtrace(string &digits, int n){
14         if(n==digits.size()){
15             ans.push_back(gen);
16             return;
17         }
18         int w=digits[n]-'0';
19         for(int i=0;i<dict[w].size();i++){
20             gen[n]=dict[w][i];
21             backtrace(digits,n+1);
22         }
23 
24     }
25 };

猜你喜欢

转载自www.cnblogs.com/rookiez/p/13192649.html