3ms C++ solution


  • 0
    W
    vector<string> letterCombinations(string digits) {
        vector<string> ret;
        if(digits != ""){
            map<char, string> int_str;
            int_str['2'] = "abc", int_str['3'] = "def", int_str['4'] = "ghi",
                int_str['5'] = "jkl", int_str['6'] = "mno", int_str['7'] = "pqrs",
                int_str['8'] = "tuv", int_str['9'] = "wxyz";
            vector<string> vecstr;        
            vector<char> curr;
            for (int i = 0; i < digits.size(); ++i)
                vecstr.push_back(int_str[digits[i]]);	
            letterCombinationsCore(ret, vecstr, curr, vecstr.size(), 0);
        }
        return ret;
    }
    
    
    void letterCombinationsCore(vector<string>& ret, vector<string>& vecstr, vector<char> curr, int n, int index) {
        if (index == n) {
            string temp = "";
            for (auto ch : curr)
                temp += ch;
            ret.push_back(temp);
            return;
        }	
    
        for (int i = 0; i < vecstr[index].size(); ++i) {
            curr.push_back(vecstr[index][i]);
            letterCombinationsCore(ret, vecstr, curr, n, index + 1);
    
            curr.pop_back();
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.