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

    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 
     3 public:
     4 
     5     vector<string> letterCombinations(string digits) {
     6 
     7         vector<string> num2string(10);
     8 
     9         num2string[0]="";
    10 
    11         num2string[1] = "";  
    12 
    13         num2string[2] = "abc";  
    14 
    15         num2string[3] = "def";  
    16 
    17         num2string[4] = "ghi";  
    18 
    19         num2string[5] = "jkl";  
    20 
    21         num2string[6] = "mno";  
    22 
    23         num2string[7] = "pqrs";  
    24 
    25         num2string[8] = "tuv";  
    26 
    27         num2string[9] = "wxyz";
    28 
    29        
    30 
    31         vector<string> result;
    32 
    33         string tmp="";
    34 
    35         combination(digits,0,tmp,num2string,result);
    36 
    37         return result;
    38 
    39     }
    40 
    41    
    42 
    43    
    44 
    45     void combination(string &digits,int index,string tmp,vector<string> &num2string,vector<string> &result)
    46 
    47     {
    48 
    49         if(index==digits.length())
    50 
    51         {
    52 
    53             result.push_back(tmp);
    54 
    55             return;
    56 
    57         }
    58 
    59        
    60 
    61         string mapString=num2string[digits[index]-'0'];
    62 
    63         for(int i=0;i<mapString.length();i++)
    64 
    65         {
    66 
    67             tmp.push_back(mapString[i]);
    68 
    69             combination(digits,index+1,tmp,num2string,result);
    70 
    71             tmp.pop_back();
    72 
    73         }
    74 
    75     }
    76 
    77 };
  • 相关阅读:
    OkHttp的使用
    Adapter的实现
    RxJava的学习与实现
    Blueprint的实现
    The second group meeting!
    读书笔记1
    The First Team Meeting!
    java----使用NIO进行快速的文件拷贝
    java——类的学习(2)
    java——类的学习(1)
  • 原文地址:https://www.cnblogs.com/reachteam/p/4192419.html
Copyright © 2011-2022 走看看