Sharing my 0ms C++ solution using recursion


  • 0
    T
    class Solution {
    private:
        void letterCombinationsHelper(string digits, string s, vector<string>& result, int start)
        {
            int n = digits.length();
            if(start==n)
            {   
                result.push_back(s);
                return;
            }
            char c = digits[start];
            char letter;
            int i;
            if(c>='2' && c<='6')
            {
                for(i=0; i<3; i++)
                {
                    letter = 'a'+(c-'2')*3+i;
                    letterCombinationsHelper(digits, s+letter, result, start+1);
                }
            }
            else if(c=='7')
            {
                for(i=0; i<4; i++)
                {
                    letter = 'p'+i;
                    letterCombinationsHelper(digits, s+letter, result, start+1);
                }   
            }
            else if(c=='8')
            {
                for(i=0; i<3; i++)
                {
                    letter = 't'+i;
                    letterCombinationsHelper(digits, s+letter, result, start+1);
                }
            }
            else if(c == '9')
            {
                for(i=0; i<4; i++)
                {
                    letter = 'w'+i;
                    letterCombinationsHelper(digits, s+letter, result, start+1);
                }
            }
            else
                exit(1);
        }
    public:
        vector<string> letterCombinations(string digits) {
            vector<string> result;
            if(digits.length() == 0)
                return result;
            string s;
            int start=0;
            letterCombinationsHelper(digits, s, result, start);
            return result;
        }
    };

Log in to reply
 

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