[Leetcode] letter combinations of a phone number 电话号码的字母组合

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.

 题意:给定数字串,输出对应字母的组合

思路:基本的DFS,这题和平常一般的DFS的区别,在于一般情况下,我们只需直接用下标进行深搜,而本题中,得先从数字串中取出一个数字,获得相应字符串以后,再在对应的字符串中获得一个字符,再在下一个数字对应的字符串中获得另一个字符,以这样的形式进行深搜整个过程类似于搜索二维数组,取数子相当于遍历行,取字母相当于遍历列。代码如下:

 1 class Solution {
 2 public:
 3     vector<string> letterCombinations(string digits) 
 4     {
 5         vector<string> res;
 6         if(digits.empty())  return {""};    //当digits为空的时候,应该返回""
 7         string dict[]={" "," ","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; 
 8         string midstr;
 9         letterDFS(digits,res,dict,midstr,0);
10         return res;
11     }
12 
13     void letterDFS(const string &digits,vector<string> &res,string dict[],string midstr, int start)
14     {
15         if(start==digits.size())    
16             res.push_back(midstr);
17         else
18         {
19             string str=dict[digits[start]-'0'];
20             for(int i=start;i<str.size();++i)
21             {
22                 midstr.push_back(str[i]);
23                 letterDFS(digits,res,dict,midstr,start+1);
24                 midstr.pop_back();
25             }
26         }
27         
28 
29     }
30 };

方法二:这种方法的思路和subset的迭代解法很像。这里因为有一个取数字串中数字的情况存在,所以,多一个for循环,其余的基本一样。如:“23” ,res中先存入“a”,"b","c",然后和“3”对应的字符相结合,后来存入"ad","ae","af",    "bd","be","bf",   "cd","ce","cf"参考了Cindy_niu的博客

 1 class Solution {
 2 public:
 3     vector<string> letterCombinations(string digits) 
 4     {
 5         vector<string> res(1,"");
 6         string dict[]={" "," ","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
 7 
 8         for(int i=0;i<digits.size();++i)
 9         {
10             vector<string> temp;
11             for(int j=0;j<res.size();++j)
12             {
13                 for(int k=0;k<dict[digits[i]-'0'].size();++k)
14                 {
15                     temp.push_back(res[j]+dict[digits[i]-'0'][k]);
16                 }
17             }
18             res=temp;
19         }     
20         return res;
21     }
22 };

 

posted @ 2017-07-13 10:18  王大咩的图书馆  阅读(292)  评论(0编辑  收藏  举报