My C++ 0ms backtracking solution


  • 0
    class Solution {
    public:
        vector<string> letterCombinations(string digits) {
            string a[10] = {" ", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
            vector<string> letters(a, a + 10);
            vector<string> results;
            if(!digits.length())
            {
                return results;
            }
            string word;
            backtracking(results, letters, digits, word);
            return results;
        }
    
        void backtracking(vector<string> &results, vector<string> &letters, string &digits, string &word)
        {
            if(word.length() == digits.length())
            {
                results.push_back(word);
                return;
            }
            int number = digits[word.length()] - '0';
            for(unsigned int i = 0; i < letters[number].length(); i++)
           {
                word.push_back(letters[number][i]);
                backtracking(results, letters, digits, word);
                word.erase(word.end() - 1);
            }
        }
    };

Log in to reply
 

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