zoukankan      html  css  js  c++  java
  • [Leetcode 47] 17 Letter Combinations of a Phone Number

    Problem:

    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"].

    Analysis:

    This is a simple backtracking problem. Backtrack method view the solution sapce as a tree. And it will go down from the root(initial state) to the leaf(some solution) to build a solution for the problem. A general structure of a backtracking program is as follows:

    void backtrack(p1, ..., pn) {

      if (current solution is a well formed solution) {

        //do something

        return;

      }

      for every child of current node

        backtrack()

    }

    With this in mind, the problem is easy to solve.

    Code:

     1 class Solution {
     2 public:
     3             vector<string> table;
     4             vector<string> res;
     5 
     6     vector<string> letterCombinations(string digits) {
     7         // Start typing your C/C++ solution below
     8         // DO NOT write int main() function
     9         if (digits.size() == 0) 
    10             return vector<string>(1,"");
    11         
    12         res.clear();
    13         table.resize(10);
    14         table[2] = "abc";
    15         table[3] = "def";
    16         table[4] = "ghi";
    17         table[5] = "jkl";
    18         table[6] = "mno";
    19         table[7] = "pqrs";
    20         table[8] = "tuv";
    21         table[9] = "wxyz";    
    22         
    23         backtrack(digits, 0, "");
    24         return res;
    25     }
    26     
    27     void backtrack(string &s, int pos, string ss) {
    28         if (pos == s.size()) {
    29             res.push_back(ss);
    30             return ;
    31         }
    32         
    33         for (int i=0; i<table[s[pos] - '0'].size(); i++) {
    34             backtrack(s, pos+1, ss+table[s[pos] - '0'][i]);
    35         }
    36         
    37         return ;
    38     }
    39 };
    View Code

    Attention:

    There are many C++ skills used in this code, learn it.

  • 相关阅读:
    C# IEnumerable 和 IEnumerator接口浅析
    SQLite笔记
    命令行工具osql.exe使用
    2016年年终工作总结
    c# Json 自定义类作为字典键时,序列化和反序列化的处理方法
    多线程随笔
    常见异步机制分析
    SQL 通过syscolumns.xtype动态查找指定数据类型字段所包含的数据
    SQL 删除索引错误
    SQL 实用函数
  • 原文地址:https://www.cnblogs.com/freeneng/p/3098627.html
Copyright © 2011-2022 走看看