Intuitive C++ recursive solution


  • 0
    R
    vector<string> letterCombinations(string digits) {
        vector<string> combo;
        if (digits == "")
            return combo;
        char* cDigits = new char[digits.length()];
        strcpy(cDigits, digits.c_str());
        cDigits[digits.length()-1] = 0;
        string letters = repLetter(digits[digits.size()-1]);
        vector <string> comboSofar = letterCombinations(cDigits);
        if (comboSofar.empty())
            comboSofar.push_back("");
        for (int i = 0; i < comboSofar.size(); i++){
            for (int j = 0; j < letters.length(); j++){
                combo.push_back(comboSofar[i]);
                combo[combo.size()-1].push_back(letters[j]);
            }
        }
        return combo;
    }
    
    string repLetter(char n){
        switch (n){
            case '2': return "abc";
            case '3': return "def";
            case '4': return "ghi";
            case '5': return "jkl";
            case '6': return "mno";
            case '7': return "pqrs";
            case '8': return "tuv";
            case '9': return "wxyz";
            case '0': return " ";
            default: return "";
        }
    }

Log in to reply
 

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