C++ DFS very clean


  • 0
    B
      vector<string> letterCombinations(string digits) {
        unordered_map<char, string> myMap = {{'2',"abc"}, {'3',"def"}, {'4',"ghi"},
        {'5',"jkl"}, {'6',"mno"}, {'7',"pqrs"}, {'8',"tuv"}, {'9',"wxyz"}};
        vector<string> res;
        dfs(digits, myMap, 0, "", res);
        return res;
    }
    
    void dfs(string digits, unordered_map<char, string> myMap, int idx, string path, vector<string>& res) {
        if (!path.empty() && path.size() == digits.size()) {
            res.push_back(path);
            return;
        }
        for (auto& c: myMap[digits[idx]]) {
            path.push_back(c);
            dfs(digits, myMap, idx+1, path, res);
            path.pop_back();
        }
    }

Log in to reply
 

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