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

    暴力方法解题。之前使用 if  if  if,超时,改成if ... else if ... else if ... 4ms。减少不必要判断还是蛮有效果的。

    class Solution {
    public:
        vector<string> re;
        vector<string> letterCombinations(string digits) {
           string result = "";
           int index = 0;
           
           letter(digits ,index , result);
           return re;
     
        }
        void letter(string s ,int i,string result)
        {
            if(i >= s.length())
            {
            re.push_back(result);
            return;
            }
            else if(s[i] == '2')
            {
            letter(s,i+1,result+'a');
            letter(s,i+1,result+'b');
            letter(s,i+1,result+'c');
            }
            else if(s[i] == '3')
            {
            letter(s,i+1,result+'d');
            letter(s,i+1,result+'e');
            letter(s,i+1,result+'f');
            }
            else if(s[i] == '4')
            {
            letter(s,i+1,result+'g');
            letter(s,i+1,result+'h');
            letter(s,i+1,result+'i');
            }
            else if(s[i] == '5')
            {
            letter(s,i+1,result+'j');
            letter(s,i+1,result+'k');
            letter(s,i+1,result+'l');
            }
            else if(s[i] == '6')
            {
            letter(s,i+1,result+'m');
            letter(s,i+1,result+'n');
            letter(s,i+1,result+'o');
            }
            else if(s[i] == '7')
            {
            letter(s,i+1,result+'p');
            letter(s,i+1,result+'q');
            letter(s,i+1,result+'r');
            letter(s,i+1,result+'s');
            }
            else if(s[i] == '8')
            {
            letter(s,i+1,result+'t');
            letter(s,i+1,result+'u');
            letter(s,i+1,result+'v');
            }
            else if(s[i] == '9')
            {
            letter(s,i+1,result+'w');
            letter(s,i+1,result+'x');
            letter(s,i+1,result+'y');
            letter(s,i+1,result+'z');
            }
            
        }
    };
  • 相关阅读:
    python之路_django入门项目(老师表)
    python之路_django入门项目(学生表)
    python之路_初识django框架
    python之路_前端基础之Bootstrap JS
    python之路_前端基础之Bootstrap 组件
    python之路_前端基础之Bootstrap CSS
    python之路_登录验证及表格增删改作业
    Spring Boot CLI安装
    Spring Boot 所提供的配置优先级顺序
    Intellij IDEA 14.x 中的Facets和Artifacts的区别
  • 原文地址:https://www.cnblogs.com/pengyu2003/p/3586413.html
Copyright © 2011-2022 走看看