美文网首页
17. Letter Combinations of a Pho

17. Letter Combinations of a Pho

作者: 蜜糖_7474 | 来源:发表于2019-05-08 10:52 被阅读0次

    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.

    AC代码

    class Solution {
    public:
        vector<string> letterCombinations(string digits) {
            if (digits.size() == 0) return {};
            vector<string> v{"abc", "def",  "ghi", "jkl",
                             "mno", "pqrs", "tuv", "wxyz"};
            int size = 1;
            for (int i = 0; i < digits.size(); ++i)
                size *= v[digits[i] - '0' - 2].size();
            vector<string> ans(size);
            int res = size;
            for (int idx = 0; idx < digits.size(); ++idx) {
                int len = v[digits[idx] - '0' - 2].size();
                for (int i = 0; i < size; ++i) {
                    ans[i] += v[digits[idx] - '0' - 2][(i / (res / len)) % len];  #核心
                }
                res /= len;
            }
            return ans;
        }
    };
    

    总结

    网上有使用递归的解法,个人不是很懂递归的思想,有时间学习后再补充解法

    相关文章

      网友评论

          本文标题:17. Letter Combinations of a Pho

          本文链接:https://www.haomeiwen.com/subject/ngtmoqtx.html