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');
            }
            
        }
    };
  • 相关阅读:
    介绍一种很好用的任务调度平台
    java中的进制与操作符
    类再生(合成、继承、final)
    初始化
    重新学习Spring2——IOC和AOP原理彻底搞懂
    重新学习Spring一--Spring在web项目中的启动过程
    JDK并发包
    java并行程序基础
    MVC模式
    访问者模式
  • 原文地址:https://www.cnblogs.com/pengyu2003/p/3586413.html
Copyright © 2011-2022 走看看