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

Letter Combinations of a Phone Number

时间:2015-10-13 01:34:13      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:

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.

 

Analyse: Be careful about the difference between empty string and non-empty string when conducting an operation. If you set an empty string, you don‘t have an access to any index, the only operation you can do is contat/‘+‘. 

Runtime: 4ms

 1 class Solution {
 2 public:
 3     vector<string> letterCombinations(string digits) {
 4         vector<string> result;
 5         if(digits.empty()) return result;
 6         
 7         string temp(digits.size(), 0);
 8         helper(digits, result, temp, 0);
 9         return result;
10     }
11     
12     void helper(string digits, vector<string>& result, string temp, int depth){
13         if(depth == digits.size()){
14             result.push_back(temp);
15             return;
16         }
17         
18         string info[] = {" ", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
19         string current = info[digits[depth] - 0]; //the size of the current string that the digit represent
20         for(int i = 0; i < current.size(); i++){
21             temp[depth] = current[i];
22             helper(digits, result, temp, depth + 1);
23         }
24     }
25 };

 

Letter Combinations of a Phone Number

标签:

原文地址:http://www.cnblogs.com/amazingzoe/p/4873347.html

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