zoukankan      html  css  js  c++  java
  • [LintCode] 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.

    Cellphone

     Notice

    Although the above answer is in lexicographical order, your answer could be in any order you want.

    Example

    Given "23"

    Return["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]

     

    LeetCode上的原题,请参见我之前的博客Letter Combinations of a Phone Number

    解法一:

    class Solution {
    public:
        /**
         * @param digits A digital string
         * @return all posible letter combinations
         */
        vector<string> letterCombinations(string& digits) {
            if (digits.empty()) return {};
            vector<string> res;
            vector<string> v{"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
            helper(digits, v, 0, "", res);
            return res;
        }
        void helper(string& digits, vector<string>& v, int level, string out, vector<string>& res) {
            if (level == digits.size()) {
                res.push_back(out);
                return;
            }
            string t = v[digits[level] - '0'];
            for (int i = 0; i < t.size(); ++i) {
                out.push_back(t[i]);
                helper(digits, v, level + 1, out, res);
                out.pop_back();
            }
        }
    };

    解法二:

    class Solution {
    public:
        /**
         * @param digits A digital string
         * @return all posible letter combinations
         */
        vector<string> letterCombinations(string& digits) {
            if (digits.empty()) return {};
            vector<string> res{""};
            vector<string> v{"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
            for (int i = 0; i < digits.size(); ++i) {
                string str = v[digits[i] - '0'];
                int n = res.size();
                for (int j = 0; j < n; ++j) {
                    string t = res.front();
                    res.erase(res.begin());
                    for (int k = 0; k < str.size(); ++k) {
                        res.push_back(t + str[k]);
                    }
                }
            }
            return res;
        }
    };

     

  • 相关阅读:
    简易高重用的jdbcutils工具封装实现类以及简易连接池实现
    http header 具体解释
    zoj 3888 Twelves Monkeys 二分+线段树维护次小值
    hyperLink的定制
    document.body.clientHeight的取值
    在循环中创建网页元素的问题
    mongo db 启动停止
    myeclipse 2014破解
    weblogic 集群部署时上传jsp不更新问题
    Spring classPath:用法
  • 原文地址:https://www.cnblogs.com/grandyang/p/5690104.html
Copyright © 2011-2022 走看看