首页 > 其他 > 详细

leetcode 17 Letter Combinations of a Phone Number

时间:2019-08-29 10:35:43      阅读:91      评论:0      收藏:0      [点我收藏+]

Given a string containing digits from 2-9 inclusive, 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. Note that 1 does not map to any letters.

技术分享图片

Example:

Input: "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 private:
 3     // 创建映射map
 4     unordered_map<char, string> num2char {{2, "abc"}, {3, "def"}, {4, "ghi"}, {5, "jkl"},
 5                                           {6, "mno"}, {7, "pqrs"}, {8, "tuv"}, {9, "wxyz"}};
 6     
 7     void letterCombinations(vector<string> &res, string &combination, string digits, int index, int len) {
 8         if (index == len) {
 9             res.push_back(combination);
10             return;
11         }
12         //遍历第index位可以选择的字符
13         for (char c : num2char[digits[index]]) {
14             combination.push_back(c);
15             letterCombinations(res, combination, digits, index + 1, len);
16             combination.pop_back();
17         } 
18         /*
19         string current = num2char[digits[index]];
20         for (int i = 0; i < current.length(); i++) {
21             combination.push_back(current[i]);
22             letterCombinations(res, combination, digits, index + 1, len);
23             combination.pop_back();
24         } */
25     }
26 public:
27     vector<string> letterCombinations(string digits) {
28     
29         int len = digits.length();
30         vector<string> res;
31         if (len == 0) {
32             return res;
33         }
34         
35         string combination;
36         letterCombinations(res, combination, digits, 0, len);
37         return res;
38     }
39 };

 

leetcode 17 Letter Combinations of a Phone Number

原文:https://www.cnblogs.com/qinduanyinghua/p/11428161.html

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