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

【leetcode】Letter Combinations of a Phone Number

时间:2014-12-29 22:56:03      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:

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 
 3 public:
 4 
 5     vector<string> letterCombinations(string digits) {
 6 
 7         vector<string> num2string(10);
 8 
 9         num2string[0]="";
10 
11         num2string[1] = "";  
12 
13         num2string[2] = "abc";  
14 
15         num2string[3] = "def";  
16 
17         num2string[4] = "ghi";  
18 
19         num2string[5] = "jkl";  
20 
21         num2string[6] = "mno";  
22 
23         num2string[7] = "pqrs";  
24 
25         num2string[8] = "tuv";  
26 
27         num2string[9] = "wxyz";
28 
29        
30 
31         vector<string> result;
32 
33         string tmp="";
34 
35         combination(digits,0,tmp,num2string,result);
36 
37         return result;
38 
39     }
40 
41    
42 
43    
44 
45     void combination(string &digits,int index,string tmp,vector<string> &num2string,vector<string> &result)
46 
47     {
48 
49         if(index==digits.length())
50 
51         {
52 
53             result.push_back(tmp);
54 
55             return;
56 
57         }
58 
59        
60 
61         string mapString=num2string[digits[index]-0];
62 
63         for(int i=0;i<mapString.length();i++)
64 
65         {
66 
67             tmp.push_back(mapString[i]);
68 
69             combination(digits,index+1,tmp,num2string,result);
70 
71             tmp.pop_back();
72 
73         }
74 
75     }
76 
77 };

 

【leetcode】Letter Combinations of a Phone Number

标签:

原文地址:http://www.cnblogs.com/reachteam/p/4192419.html

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