zoukankan      html  css  js  c++  java
  • leetcode 17. Letter Combinations of a Phone Number

    Given a string containing digits from 2-9 inclusive, 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. Note that 1 does not map to any letters.

    Example:

    Input: "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.

    用迭代的方法来实现;

    初始答案为ans=“”;

    出现一个数字就把该数字对于按键上所有的字母和之前的组合依次相加,遍历输入字符串的每一个数字就能得到所有 的组合;

    用数组num保存每一按键第一个字母在字母表中的位置, 方便计算

    注意点:输入可能是空字符串,需要单独处理

     1 class Solution {
     2 public:
     3     vector<string> letterCombinations(string digits) {
     4         vector<string> ans;
     5         if(digits=="") return ans;
     6         ans.push_back("");
     7         char ch[]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
     8         int num[11]={0,0,0,3,6,9,12,15,19,22, 26};
     9         for(int i=0; i<digits.size(); i++){
    10             vector<string> temp;
    11             int cnt=num[digits[i]-'0'+1] - num[digits[i]-'0'], idx=num[digits[i]-'0'];
    12             for(int j=0; j<ans.size(); j++){
    13                 for(int k=0; k<cnt; k++) temp.push_back(ans[j]+ch[idx+k]);
    14             }
    15             ans = temp;
    16         }
    17         return ans;
    18     }
    19 };
    有疑惑或者更好的解决方法的朋友,可以联系我,大家一起探讨。qq:1546431565
  • 相关阅读:
    Bzoj1101 [POI2007]Zap
    Bzoj2393 Cirno的完美算数教室
    UVa10891 Game of Sum
    Bzoj4128 Matrix
    类的组合
    继承
    属性查找与绑定方法
    类与对象
    面向对象程序设计——基础概念
    修改个人信息的程序
  • 原文地址:https://www.cnblogs.com/mr-stn/p/9220481.html
Copyright © 2011-2022 走看看