• [LeetCode] 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.

    用一个array保存数字对应的字符,再用dfs枚举所有解

     1 class Solution {
     2 private:
     3     map<char, vector<char> > dict;
     4     vector<string> ret;
     5 public:
     6     void createDict()
     7     {
     8         dict.clear();
     9         dict['2'].push_back('a');
    10         dict['2'].push_back('b');
    11         dict['2'].push_back('c');
    12         dict['3'].push_back('d');
    13         dict['3'].push_back('e');
    14         dict['3'].push_back('f');
    15         dict['4'].push_back('g');
    16         dict['4'].push_back('h');
    17         dict['4'].push_back('i');
    18         dict['5'].push_back('j');
    19         dict['5'].push_back('k');
    20         dict['5'].push_back('l');
    21         dict['6'].push_back('m');
    22         dict['6'].push_back('n');
    23         dict['6'].push_back('o');
    24         dict['7'].push_back('p');
    25         dict['7'].push_back('q');
    26         dict['7'].push_back('r');
    27         dict['7'].push_back('s');
    28         dict['8'].push_back('t');
    29         dict['8'].push_back('u');
    30         dict['8'].push_back('v');
    31         dict['9'].push_back('w');
    32         dict['9'].push_back('x');
    33         dict['9'].push_back('y');
    34         dict['9'].push_back('z');
    35     }
    36     
    37     void dfs(int dep, int maxDep, string &s, string ans)
    38     {
    39         if (dep == maxDep)
    40         {
    41             ret.push_back(ans);
    42             return;
    43         }
    44         
    45         for(int i = 0; i < dict[s[dep]].size(); i++)
    46             dfs(dep + 1, maxDep, s, ans + dict[s[dep]][i]);
    47     }
    48     
    49     vector<string> letterCombinations(string digits) {
    50         // Start typing your C/C++ solution below
    51         // DO NOT write int main() function
    52         ret.clear();
    53         createDict();
    54         dfs(0, digits.size(), digits, "");
    55         return ret;
    56     }
    57 };
  • 相关阅读:
    IE绝对定位元素神秘消失或被遮挡的解决
    14条最佳JS代码编写技巧
    Query中的$.getJSON
    理解JavaScript中的对象
    Javascript的IE和Firefox兼容性汇编
    window.location 与 window.location.href
    认识hasLayout主要IE浏览器css bug的一大罪恶根源
    C/C++版数据结构之排序算法
    C++关键字mutable
    C++关键字explicit
  • 原文地址:https://www.cnblogs.com/chkkch/p/2765976.html
Copyright © 2020-2023  润新知