Why runtime error with input "2"?


  • 0
    J

    I think my solution is pretty standard DFS. why it has runtime error? Thanks.

    class Solution {
    public:
        vector<string> letterCombinations(string digits) {
            vector<string> vec;
            string str;
            unordered_map<char, string> map{{'2', "abc"},{'3', "def"}, {'4',"ghi"},{'5',"jkl"}, {'6', "mno"},{'7',"pqrs"},{'8',"tuv"},{'9',"wxyz"}};
            helper(digits, map, 0, str, vec);
            return vec;
            
        }
        void helper(string &digits, unordered_map<char,string> &map, int index, string &str, vector<string> &vec) {
            if(str.size()==digits.size()) {
                vec.push_back(str);
                return;
            }
            for(int i=index; i<digits.size(); ++i) {
                for(int j=0; j<map[digits[i]].size(); j++) {
                    str+=map[digits[i]][j];
                    helper(digits, map, index+1, str, vec);
                    //remove last char
                    str.erase(str.end());
                }
            }
        }
    };

Log in to reply
 

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