My easy to understand non-recursive C++ solution


  • 0
    E
    vector<string> letterCombinations(string digits) {
        vector<string> ret;
        if(digits.empty())
            return ret;
        map<char, vector<char> > m;
        m['0'] = {' '};
        m['2'] = {'a', 'b', 'c'};
        m['3'] = {'d', 'e', 'f'};
        m['4'] = {'g', 'h', 'i'};
        m['5'] = {'j', 'k', 'l'};
        m['6'] = {'m', 'n', 'o'};
        m['7'] = {'p', 'q', 'r', 's'};
        m['8'] = {'t', 'u', 'v'};
        m['9'] = {'w', 'x', 'y', 'z'};
        vector<vector<char> > char_list;
        for(auto a : digits)
            char_list.push_back(m[a]);
        ret = {""};
        for(auto list : char_list)
        {
            vector<string> temp;
            for(auto str : ret)
            {
                for(auto ch : list)
                {
                    temp.push_back(str + ch);
                }
            }
            ret = temp;
        }
        return ret;
    }

Log in to reply
 

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