0m C++ solutions using backtracing


  • 0
    class Solution {
    public:
        vector<string> letterCombinations(string digits) {
            vector<string> result;
            
            if(digits.length() == 0)
            {
                return result;
            }
            
            string currentStr = "";
            
            // initialize all combinations
            vector<string> combo({"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"});
            
            
            GetCombinations(digits, combo, currentStr, result, 0);
            
            return result;
        }
        
        void GetCombinations(string digits, vector<string>& combo, string& currentStr, vector<string>& result, int index)
        {
            
            if(currentStr.length() == digits.length())
            {
                result.push_back(currentStr);
                return;
            }
            
            // convert the character type digit to number digit
            char c = digits[index];
            string currentCombo = combo[c-'0']; 
            
            for(int i = 0; i< currentCombo.length(); i++)
            {
                currentStr += currentCombo[i];
                
                GetCombinations(digits, combo, currentStr, result, index+1);
                
                // pop the last character out
                currentStr = currentStr.substr(0, currentStr.length()-1);
            }
        }
    };
    
    

Log in to reply
 

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