zoukankan      html  css  js  c++  java
  • 【Leetcode】【Medium】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.

    解题思路:

    需要穷举不同中排列可能,典型需要回溯的思想;

    可以选择递归或非递归的形式实现回溯;

    递归:

     1 class Solution {
     2 public:
     3     vector<string> letterCombinations(string digits) {
     4         vector<string> lst;
     5         string ans;
     6         if (digits == "")
     7             return lst;
     8         Backtracking(lst, ans, digits, 0);
     9         return lst;
    10     }
    11     
    12     void Backtracking(vector<string> &lst, string ans, string digits, int idx) {
    13         if (idx == digits.size()) {
    14             lst.push_back(ans);
    15             return;
    16         }
    17         string cur_chars = d2l[digits[idx] - '0'];
    18         for (int i = 0; i < cur_chars.size(); ++i) 
    19             Backtracking(lst, ans + cur_chars[i], digits, idx + 1);
    20     }
    21 
    22 private:
    23     vector<string> d2l = {
    24         " ", "", "abc", "def", "ghi", "jkl",
    25         "mno", "pqrs", "tuv", "wxyz"
    26     };
    27 };

    非递归:

  • 相关阅读:
    WEB服务器和应用服务器
    java中乱码问题
    面向对象的特征
    数据库中常见的需注意的问题
    String类
    网络编程
    C#泛型基础
    C#中sealed关键字的作用。
    C#自动属性优缺点分析
    TextView属性(转)
  • 原文地址:https://www.cnblogs.com/huxiao-tee/p/4242874.html
Copyright © 2011-2022 走看看