LeetCode - 17. Letter Combinations of a Phone Number - C++

借鉴的这个博客,理解之后改为自己的风格

解法一

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        vector<string> result;
        if(digits.empty()) return result;
        string dictionary[] = {"", "",
                               "abc", "def", "ghi", "jkl",
                               "mno", "pqrs", "tuv", "wxyz"};
        letterCombinationDFS(digits, dictionary, 0, "", result);
        return result; 
    }
    
    void letterCombinationDFS(string digits, string dictionary[], 
                            int level, string current, 
                            vector<string>& result) {
        
        if(level == digits.size()) {
            result.push_back(current);
            return;
        } 
        
        string s = dictionary[digits[level]-'0'];
        
        for(int i=0; i<s.size(); i++) {
            
            letterCombinationDFS(digits, dictionary, 
                                 level+1, current+s[i], result);
        }          
    }
};

解法二

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        if (digits.empty()) return {};
        vector<string> result{""};
        
        string dictionary[] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        
        for (int i = 0; i < digits.size(); i++) {
            vector<string> temp;
            string s = dictionary[digits[i] - '0'];
            for (int j=0; j<result.size(); j++) {
                for (int k=0; k<s.size(); k++) {
                    temp.push_back(result[j] + s[k]);
                }
            }
            result = temp;
        }
        return result;
    }
};

用数组作map,访问的时候 -‘0’,挺妙的。

没什么好说的,题挺规矩,自己做不出,多练。

猜你喜欢

转载自blog.csdn.net/L_bic/article/details/89228246
今日推荐