码迷,mamicode.com
首页 > 其他好文 > 详细

Letter Combinations of a Phone Number

时间:2014-09-16 00:05:09      阅读:405      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   os   ar   strong   for   

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.

bubuko.com,布布扣

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 };

 

Letter Combinations of a Phone Number

标签:style   blog   http   color   io   os   ar   strong   for   

原文地址:http://www.cnblogs.com/bugfly/p/3973935.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!