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.

 

主要是建立数字字母映射表,然后依次对每个数字所对应的字母进行深搜,代码如下:

 1 class Solution {
 2 public:
 3     vector<string> letterCombinations(string digits) {
 4         vector<string> vstr(9); //建立数字映射字母表
 5         char ch = 'a';
 6         for(int i=1; i<9; ++i) {
 7             if( i == 6 || i == 8) {
 8                 int cnt = 4;
 9                 while( cnt-- ) vstr[i].push_back(ch++);
10             }
11             else {
12                 int cnt = 3;
13                 while( cnt-- ) vstr[i].push_back(ch++);
14             }
15         }
16         ans.clear();
17         string str;
18         dfs(digits, vstr, 0, str);  //深搜
19         return ans;
20     }
21     
22     void dfs(string& digits, vector<string>& vstr, int k, string& str) {
23         if( k == digits.length() ) {    //如果搜到了末尾,str就是答案之一
24             ans.push_back(str);
25             return;
26         }
27         int index = digits[k]-'0'-1;    //取对应数字在映射表中的位置
28         for(int i=0; i<vstr[index].size(); ++i) {   //对每个数字所代表字母的进行深搜
29             str.push_back(vstr[index][i]);
30             dfs(digits, vstr, k+1, str);
31             str.pop_back();
32         }
33     }
34     
35 private:
36     vector<string> ans;
37 };

 

posted on 2014-09-15 22:55  bug睡的略爽  阅读(188)  评论(0编辑  收藏  举报

导航