My recursive cpp code


  • 0
    C
    class Solution {
    public:
        
        string digit2charset(char c)
        {
            switch(c)
            {
                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";
                default:  return "";
            }
        }
        
        vector<string> helper(const string &digits, int digits_id)
        {
            vector<string> result;
            
            string choices = digit2charset(digits[digits_id]);
            
            if(digits_id == digits.size()-1) 
            {
                for(char c : choices)
                    result.push_back( string(1, c) );
                return result;
            }
            
            vector<string> vec = helper(digits, digits_id+1);
                
            for(char c : choices)
            {
                for(string str : vec)
                {
                    str.push_back(c);
                    result.push_back(str);
                }
            }
            
            return result;
        }
        
        vector<string> letterCombinations(string digits) 
        {
            if(digits.size() == 0) return vector<string>();
            
            std::reverse(digits.begin(), digits.end());
            
            return helper(digits, 0);
        }
    };

Log in to reply
 

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