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 };

    非递归:

  • 相关阅读:
    cefsharp设置默认语言
    C#创建委托实例
    C++/C#互调步骤
    mybatis别名
    redis
    数据库优化方面的事情:
    Properties类使用详解
    七层协议以及如何很好得记忆
    Http 请求到后端过程
    【转】那些年用过的Redis集群架构(含面试解析)
  • 原文地址:https://www.cnblogs.com/huxiao-tee/p/4242874.html
Copyright © 2011-2022 走看看