C++ tail recursive solution


  • 0
    B
    class Solution {
    public:
        vector<string> letterCombinations(string digits) {
            if (digits.length() == 0) {
                return vector<string>();
            }
            
            return getCombinations({ "" }, digits);
        }
        
        vector<string> getCombinations(const vector<string>& prefixes, const string& tail) {
            static string alphabet[] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
            
            if (tail.length() == 0) {
                return prefixes;
            }
            
            auto index = static_cast<int>(tail[0]) - 48 - 2;
            if (index < 0) {
                return prefixes;
            }
            
            vector<string> newPrefixes;
            newPrefixes.reserve(prefixes.size() * alphabet[index].length());
    
            for (const auto& p : prefixes) {
                for (const auto& c : alphabet[index]) {
                    newPrefixes.push_back(p + c);
                }
            }
            
            return getCombinations(newPrefixes, tail.substr(1)); 
        }
    };
    

Log in to reply
 

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