C++ iterative solution in 0 ms


  • 0
    D

    Iterative solution simply use a deque:

    vector<string> letterCombinations(string digits) {
            deque<string> res; res.push_back("");
            map<char, string> dmap = { {'2',"abc"},{'3',"def"},{'4',"ghi"}, {'5',"jkl"},{'6',"mno"},{'7',"pqrs"},{'8',"tuv"},{'9',"wxyz"} };
            
            if (digits == "") return vector<string> (0);
            for(auto d: digits) {
                int s = res.size();
                for(int i = 0; i < s; i++) {
                    auto y = res.front(); res.pop_front();
                    for(auto x: dmap[d])
                        res.push_back(y + x);
                }
            }
            return vector<string> (res.begin(), res.end());
        }
    

Log in to reply
 

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