• 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

    Code:

    class Solution {
    public:
        int len;
        void combine(int n, string s, vector<string> &res){
            if(n==len)
                res.push_back(s);
            else
                for(int i=0;i<res[n].size();i++)
                    combine(n+1,s+res[n][i],res);
        }
        vector<string> letterCombinations(string digits) {
            vector<string> res;
            len=digits.size();
            string letters[] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
            for(int i=0;i<len;i++){
                if(digits[i]!='0'&&digits[i]!='1')
                    res.push_back(letters[digits[i]-'2']);
            }
            combine(0,"",res);
            res.erase(res.begin(),res.begin()+len);
            return res;
        }
    };

    Another answer:

    class Solution {
    public:
        vector<string> letterCombinations(string digits) {
            const string letters[] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
    
            vector<string> ret(1, "");
            for (int i = 0; i < digits.size(); ++i) {
                for (int j = ret.size() - 1; j >= 0; --j) {
                    const string &s = letters[digits[i] - '2'];
                    for (int k = s.size() - 1; k >= 0; --k) {
                        if (k)
                            ret.push_back(ret[j] + s[k]);
                        else
                            ret[j] += s[k];
                    }
                }
            }
    
            return ret;
        }
    };
  • 相关阅读:
    Eval版的ASP木马原理解析
    cmd命令
    Eval版的ASP木马原理解析
    Vbs脚本实现radmin终极后门
    迅雷是如何识别并偷偷上传文件的?
    迅雷是如何识别并偷偷上传文件的?
    广外男生病毒代码剖析
    cmd命令
    Vbs脚本实现radmin终极后门
    广外男生病毒代码剖析
  • 原文地址:https://www.cnblogs.com/winscoder/p/3438060.html
Copyright © 2020-2023  润新知