C++ Recursive solution 0ms


  • 0
    T
    class Solution {
    public:
        vector<string> res;
        int n;
        vector<int> idx;
        string combination;
        string a[26]={"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
        void f(int x, string& digits) {
            if(x==n) {
                if(combination!="") res.push_back(combination);
                return;
            }
            
            while(idx[x]<a[digits[x]-'0'-2].length()) {
                combination[x]=a[digits[x]-'0'-2][idx[x]];
                f(x+1,digits);
                idx[x]++;
            }
            idx[x]=0;
        }
        
        vector<string> letterCombinations(string digits) {
            n=digits.length();
            combination.resize(n);
            idx.resize(n,0);
            f(0,digits);
            return res;
        }
    };
    

Log in to reply
 

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