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

    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;
        }
    };
  • 相关阅读:
    Windows 7任务栏图标特别说明
    Linux下send函数 Broken pipe错误的解决方法
    C++实现一个简单的异常日志记录类
    C++写日志操作
    VC中设置打开文件的权限为管理员权限
    MFC 注册热键
    监控Tomcat状态及配置AIO(APR)模式
    Tomcat管理功能使用及WEB站点部署
    Tomcat多实例配置
    基于端口主机的虚拟主机
  • 原文地址:https://www.cnblogs.com/winscoder/p/3438060.html
Copyright © 2011-2022 走看看