My C++ Recursive solution


  • 0
    S
    void addLetterCombo(int index, string combStr, vector<string>& wordArr, vector<string>& result)
     {
            for(int i=0; i < wordArr[index].length(); i++)
            {
                if(index == 0)
                {
                    result.push_back(combStr+wordArr[index].at(i));
                }
                else
                {
                   addLetterCombo(index-1, combStr+wordArr[index].at(i), wordArr, result);
                }
            }
    }
        
    vector<string> letterCombinations(string digits) {
            vector<string> keyPad = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
            vector<string> result;
            vector<string> wordArr;
            if(!digits.empty())
            {
                for(int i=digits.length()-1 ; i >=0 ; i--)
                {
                    if((digits[i] >= '2') && (digits[i] <= '9'))
                    {
                        wordArr.push_back(keyPad[(int)(digits[i]-'2')]);
                    }
                }
                if(wordArr.size() > 0)
                  addLetterCombo(wordArr.size()-1, string(""), wordArr, result);
                }
            return result;
     }
    

Log in to reply
 

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