Letter Combinations of a Phone Number

时间:2014-04-29 19:31:07   收藏:0   阅读:524
mamicode.com,码迷
思路很简单,就是通过map对应,随后通过递归调用,这里遇到了个问题就是开始用string &re ,然后往里传re+c是不可以的,本来想省点内存,结果不行,所以只能值传递了,后来才知道string
竟然还有push_back()和pop_back(),服了。
1
class Solution { 2 public: 3 map<char,string> m; 4 int length; 5 vector<string> result; 6 vector<string> letterCombinations(string digits) { 7 m[2]="abc"; 8 m[3]="def"; 9 m[4]="ghi"; 10 m[5]="jkl"; 11 m[6]="mno"; 12 m[7]="pqrs"; 13 m[8]="tuv"; 14 m[9]="wxyz"; 15 int n=digits.length(); 16 // vector<string> a; 17 // if(n==0) return a; 18 length=n; 19 string re=""; 20 letterComb(digits,m,0,re); 21 return result; 22 } 23 void letterComb(string &digits,map<char,string> & m,int n,string re) //这里用的值传递 24 { 25 if(n==length) 26 { 27 result.push_back(re); 28 return; 29 } 30 string tmp=m[digits[n]]; 31 int l=tmp.length(); 32 for(int i=0;i<l;i++) 33 { 34 char c=tmp[i]; 35 letterComb(digits,m,n+1,re+c); //string 类型可以加上char类型哦 36 } 37 } 38 39 };

这里map还可以用

string str[8]={"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};替代,只是注意每次要减‘2’,
string tmp=str[digits[i]-‘2‘]
或者用 string strT[10] = {"","","abc","def","ghi","jkl","mno","qprs","tuv","wxyz"}; 这样是对应的,递归方法相同
修改后方法如下:
mamicode.com,码迷
 1 class Solution {
 2 public:
 3     vector<string> result;
 4     int length;
 5     string m[8]={"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
 6     
 7     vector<string> letterCombinations(string digits) {
 8     int n=digits.length();
 9     length=n;
10     string re="";
11     letterComb(digits,0,re);
12     return result;
13     }
14    void letterComb(string &digits,int n,string &re)
15    {
16          if(n==length)
17         {
18              result.push_back(re);
19              return;
20         }
21         string tmp=m[digits[n]-2];
22         int l=tmp.length();
23         for(int i=0;i<l;i++)
24         {
25               re.push_back(tmp[i]);               //这里string用push_back()和pop_back(),我也是第一次发现别人能这么用,厉害啊
26               letterComb(digits,n+1,re);
27               re.pop_back();
28         }
29    }
30 
31 };
mamicode.com,码迷

 

方法二:还有个不递归的方法

mamicode.com,码迷
 1 class Solution {
 2 public:
 3     vector<string> letterCombinations(string digits) {
 4     int n=digits.size();
 5     vector<string> result(1,"");
 6     string m[8]={"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
 7     for(int i=0;i<n;i++)
 8     {
 9         string s=m[digits[i]-2];
10         int l=s.size();
11 int size=result.size();
11 for(int j=0;j<=size-1;j++) //一定注意这里,必须先取得result.size(),否则会造成死循环 12 { 13 for(int k=0;k<l;k++) 14 { 15 if(k==l-1) //当是最后一个时,就不能再push啦,不然就重了,要把自己改了 16 { 17 result[j]+=s[k]; 18 } 19 else 20 { 21 result.push_back(result[j]+s[k]); 22 } 23 } 24 } 25 } 26 return result; 27 28 } 29 30 };
mamicode.com,码迷

 

 
mamicode.com,码迷

 

Letter Combinations of a Phone Number,码迷,mamicode.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!