C++ DP in 3ms F(n) = “(“ + F(i) + “)” + F(n-i-1)


  • 0
    G
    class Solution {
    public:
        vector<string> generateParenthesis(int n) {
            vector<vector<string>> vv(n+1);
            vv[0] = {""};
            if (n > 0) vv[1] = {"()"};
            for (int i = 2; i <= n; i++) {
                for (int j = 0; j < i; j++) {
                    for (const string& sl : vv[j]) {
                        for (const string& sr : vv[i-j-1]) {
                            vv[i].push_back("(" + sl + ")" + sr);
                        }
                    } 
                }
            }
            return vv[n];
        }
    };

Log in to reply
 

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