[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.

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;
    }
};

本文转自博客园Grandyang的博客,原文链接:电话号码的字母组合[LintCode] Letter Combinations of a Phone Number ,如需转载请自行联系原博主。

相关文章
|
存储 算法
[leetcode/lintcode 题解] 阿里算法面试真题:丑数 II · Ugly Number II
[leetcode/lintcode 题解] 阿里算法面试真题:丑数 II · Ugly Number II
[leetcode/lintcode 题解] 阿里算法面试真题:丑数 II · Ugly Number II
|
Java 数据安全/隐私保护
[LintCode] Number of Islands(岛屿个数)
描述 给一个01矩阵,求不同的岛屿的个数。 0代表海,1代表岛,如果两个1相邻,那么这两个1属于同一个岛。我们只考虑上下左右为相邻。 样例 在矩阵: [ [1, 1, 0, 0, 0], [0, 1, 0, 0, 1], [0, 0, 0, 1, 1], [0, 0, 0, 0, 0], [0, 0, 0, 0, 1] ] 中有 3 个岛。
1245 0
|
机器学习/深度学习