LeetCode - Letter Combinations of a Phone Number

解法一:non-recursion

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        unordered_map<char, string> source = {{'2',"abc"}, {'3',"def"}, {'4',"ghi"}, 
                                             {'5',"jkl"}, {'6',"mno"}, {'7',"pqrs"},
                                             {'8',"tuv"}, {'9',"wxyz"}};
        vector<string> res;
        if(digits.empty()) return res;
        res.push_back("");
        for(int i=0;i<digits.size();i++){
            string t = source[digits[i]];
            int n = res.size();
            for(int j=0;j<n;j++){
                for(int k=0;k<t.size();k++){
                    res.push_back(res.front()+t[k]);
                }
                res.erase(res.begin());
            }
        }
        return res;
    }   
};

解法二:recursion

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        unordered_map<char, string> source = {{'2',"abc"}, {'3',"def"}, {'4',"ghi"}, 
                                             {'5',"jkl"}, {'6',"mno"}, {'7',"pqrs"},
                                             {'8',"tuv"}, {'9',"wxyz"}};
        vector<string> res;
        if(digits.empty()) return res;
        gen(digits, source, 0, "", res);
        return res;
    }
    void gen(string& digits, unordered_map<char, string>& source, int pos, string out, vector<string>& res){
        if(pos==digits.size()) res.push_back(out);
        else{
            string t = source[digits[pos]];
            for(int j=0;j<t.size();j++){
                out.push_back(t[j]);
                gen(digits, source, pos+1, out,res);
                out.pop_back();
            }
        }
        
    }
};

猜你喜欢

转载自blog.csdn.net/real_lisa/article/details/82935373
今日推荐