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

    /*
     * @lc app=leetcode id=17 lang=cpp
     *
     * [17] Letter Combinations of a Phone Number
     *
     * https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/
     *
     * algorithms
     * Medium (40.64%)
     * Total Accepted:    360.2K
     * Total Submissions: 883.9K
     * Testcase Example:  '"23"'
     *
     * 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.
     * 
     */
    class Solution {
    public:
        vector<string> letterCombinations(string digits) {
            vector<string> answer;
    
            if(digits == "") return answer;
            vector<string> dict(10);
            dict[2] = "abc";
            dict[3] = "def";
            dict[4] = "ghi";
            dict[5] = "jkl";
            dict[6] = "mno";
            dict[7] = "pqrs";
            dict[8] = "tuv";
            dict[9] = "wxyz";
    
            answer.push_back("");
            for(int i = 0;i < digits.length(); ++i){
                int origin = answer.size();
    
                int len = dict[digits[i] - '0'].length();
    
                if(!len) continue;
    
                answer.resize(answer.size()*len);
                for(int j = len;j > 0;--j){
                    for(int k = 0;k < origin;++k){
                        answer[origin*j + k - origin] = answer[k] + dict[digits[i] - '0'][j-1];
                    }
                }
            }
            return answer;
        }
    };
    
    

    这位兄台 的解法更巧妙,每次erase一个,添加3到四个。

  • 相关阅读:
    Linux文件权限学习总结
    【转】Hibernate和ibatis的比较
    Spring AOP原理及拦截器
    Spring AOP (下)
    Spring AOP (上)
    SQL语句限定查询知识点总结
    多线程知识点总结
    关于tomcat那些事情
    java.lang.NoClassDefFoundError: org/apache/commons/codec/DecoderException 的解决办法
    cacti 与 nagios 一些总结 【八】
  • 原文地址:https://www.cnblogs.com/walnuttree/p/10598812.html
Copyright © 2011-2022 走看看