美文网首页
5.Letter Combinations of a Phone

5.Letter Combinations of a Phone

作者: Anaven | 来源:发表于2017-01-02 12:03 被阅读0次

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

    class Solution {
    public:
        vector<string> letterCombinations(string digits) {
            map<char, string> keyboard;
            keyboard['2'] = "abc";
            keyboard['3'] = "def";
            keyboard['4'] = "ghi";
            keyboard['5'] = "jkl";
            keyboard['6'] = "mno";
            keyboard['7'] = "pqrs";
            keyboard['8'] = "tuv";
            keyboard['9'] = "wxyz";
            keyboard['*'] = "+";
            keyboard['0'] = " ";
            
            vector<string> rst;
            string sol = "";
            
            if (digits.length() == 0) {
                return rst;
            }
            
            letterCombinations(digits, 0, sol, rst, keyboard);
            
            return rst;
        }
        
        void letterCombinations(const string &digits, int pos, string &sol, vector<string> &rst, map<char, string> &keyboard) {
            if (sol.length() == digits.length()) {
                rst.push_back(sol);
                return;
            }
            
            string candi = keyboard[digits[pos]];
            
            for (int i = 0; i < candi.length(); i++) {
                sol.push_back(candi[i]);
                letterCombinations(digits, pos+1, sol, rst, keyboard);
                sol.pop_back();
            }
        }
    };
    

    相关文章

      网友评论

          本文标题:5.Letter Combinations of a Phone

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