首页 > 其他 > 详细

[LeetCode]Letter Combinations of a Phone Number

时间:2015-12-25 23:48:34      阅读:306      评论: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.

解题思路:

递归方式,深度优先搜索

 1 class Solution {
 2 public:
 3     vector<string> letterCombinations(string digits) {
 4         vector<string> result;
 5         if (digits == "") return result;
 6         vector<string> keyboard {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
 7         string midResult(digits.size(), \0);
 8         dfs(digits, 0, midResult, keyboard, result);
 9         return result;
10     }
11 private:
12     void dfs(const string &digits, int index, string &midResult, const vector<string> &keyboard, vector<string> &result) {
13         if (index == digits.size()) {
14             result.push_back(midResult);
15             return;
16         }
17         
18         char c = digits[index];
19         for (int i = 0; i < keyboard[c - 0].size(); ++i) {
20             midResult[index] = keyboard[c - 0][i];
21             dfs(digits, index + 1, midResult, keyboard, result);
22         }
23     }
24 };

 

[LeetCode]Letter Combinations of a Phone Number

原文:http://www.cnblogs.com/skycore/p/5077213.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!