[backtracking] Concise C++ 0 ms easy to understand


  • 0
        vector<string> letterCombinations(string digits) {
            vector<string> res;
            if(digits.size()==0) return res;
            string s="";
            s.resize(digits.size());
            unordered_map<char,vector<int>>m({{'2',{'a','b','c'}},
                                              {'3',{'d','e','f'}},
                                              {'4',{'g','h','i'}},
                                              {'5',{'j','k','l'}},
                                              {'6',{'m','n','o'}},
                                              {'7',{'p','q','r','s'}},
                                              {'8',{'t','u','v'}},
                                              {'9',{'w','x','y','z'}}});
            DFS(m,digits,0,res,s);
            return res;
        }
        
        void DFS(unordered_map<char,vector<int>>&m, string digits, int l, vector<string>& res, string& s){
            if(l==digits.size()){
                res.push_back(s);
                return;
            }
            for(int i=0;i<m[digits[l]].size();i++){
                s[l]=m[digits[l]][i];
                DFS(m,digits,l+1,res,s);
            }
            return;
        } 
    

Log in to reply
 

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