my simple c++ solution


  • 1
    B
        vector<string> letterCombinations(string digits) {
            vector<string> ans;
            vector<string> ref = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
            int len = digits.size();
            if (len == 0) return ans;
            
            vector<int> ind(len, 0);
            while (true) {
                string temp = "";
                for (int i = 0; i < len; i++) {
                    temp.push_back(ref[digits[i] - '2'][ind[i]]);
                }
                ans.push_back(temp);
                ind[len - 1]++;
                for (int i = len - 1; i >= 0; i--) {
                    if (ind[i] == ref[digits[i] - '2'].size()) {
                        ind[i] = 0;
                        if (i == 0) return ans;
                        else ind[i - 1]++;
                    }
                }
            }
            return ans;
        }
    

Log in to reply
 

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