美文网首页Leetcode
Leetcode 17. Letter Combinations

Leetcode 17. Letter Combinations

作者: SnailTyan | 来源:发表于2018-09-26 18:34 被阅读4次

    文章作者:Tyan
    博客:noahsnail.com  |  CSDN  |  简书

    1. Description

    Letter Combinations of a Phone Number

    2. Solution

    class Solution {
    public:
        vector<string> letterCombinations(string digits) {
            vector<string> result;
            int n = digits.length();
            if(n == 0) {
                return result;
            }
            map<char, string> m = { 
                {'2', "abc"}, 
                {'3', "def"}, 
                {'4', "ghi"}, 
                {'5', "jkl"}, 
                {'6', "mno"}, 
                {'7', "pqrs"}, 
                {'8', "tuv"}, 
                {'9', "wxyz"}
            };
            vector<string> values;
            for(char ch : digits) {
                values.push_back(m[ch]);
            }
            traverse(result, values, n, 0, "");
            return result;
        }
    
    private:
        void traverse(vector<string>& result, vector<string>& values, int& n, int current, string s) {
            if(current == n) {
                result.push_back(s);
                return;
            }
            for(char ch : values[current]) {
                string temp = s;
                temp += ch;
                traverse(result, values, n, current + 1, temp);
            }
        }
    };
    

    Reference

    1. https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/

    相关文章

      网友评论

        本文标题:Leetcode 17. Letter Combinations

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