Letter Combinations of a Phone Number

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Letter Combinations of a Phone Number相关的知识,希望对你有一定的参考价值。

遍历所有的可能。

 1 class Solution {
 2     private:
 3     vector<string> res;
 4     map<char,string> num;
 5 public:
 6    void initial()
 7    {
 8        
 9         num[2]="abc";
10         num[3]="def";
11         num[4]="ghi";
12         num[5]="jkl";
13         num[6]="mno";
14         num[7]="pqrs";
15         num[8]="tuv";
16         num[9]="wxyz";  
17    }
18       
19     void dfsdigits(int layer,int depth,string digits,string ans)
20     {
21         if(layer==depth)
22        {
23            res.push_back(ans);
24            return ;
25        }
26        for(int i=0;i<num[digits[layer]].size();i++)
27        {
28            dfsdigits(layer+1,depth,digits,ans+num[digits[layer]][i]);
29        }
30     }
31     vector<string> letterCombinations(string digits) {
32         if(digits.empty()) return res;
33         initial();
34        
35        dfsdigits(0,digits.size(),digits,"");
36        return res;
37     }
38     
39 };

 

下面这种是循环,设中间变量

class Solution {
public:
   
    vector<string> letterCombinations(string digits) {
       vector<string> res;
       string num[10]={"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
       if(digits.empty()) return res;
       res.push_back("");
       for(int i=0;i<digits.size();i++)
       {
           vector<string> temp;
           for(int j=0;j<num[digits[i]-0].size();j++)
             for(int k=0;k<res.size();k++)
             temp.push_back(res[k]+num[digits[i]-0][j]);
             res=temp;
       }
         
         
       return res;
    }
    
};

 

以上是关于Letter Combinations of a Phone Number的主要内容,如果未能解决你的问题,请参考以下文章

17. Letter Combinations of a Phone Number

[LeetCode]Letter Combinations of a Phone Number

Letter Combinations of a Phone Number

Leetcode 17. Letter Combinations of a Phone Number

Letter Combinations of a Phone Number

17. Letter Combinations of a Phone Number