zoukankan      html  css  js  c++  java
  • leetcode 17 Letter Combinations of a Phone Number

    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 };
  • 相关阅读:
    【转载】实用VC++6.0插件
    关于无标题栏窗口拖动的问题
    VC6配置CXimage库
    扎实基础深入篇(七):函数和类没那么复杂
    扎实基础深入篇(六):while循环带动生产力
    扎实基础深入篇(五):字典也就是个弟弟
    扎实基础深入篇(四):听说if语句很叼?
    lxml类库的xpath的使用
    json与re的再次复习
    python基础汇总(四)
  • 原文地址:https://www.cnblogs.com/qinduanyinghua/p/11428161.html
Copyright © 2011-2022 走看看