Non-recursive solution


  • 0
    C

    I didn't find a 0ms solution.

    class Solution {
    public:
        vector<string> generateParenthesis(int n) {
            vector<vector<string>> f(n + 1, vector<string>());
            f[0].push_back("");
            for (int i = 1; i <= n; ++i)
                f[i].push_back(f[i - 1].back() + "(");
            for (int j = 1; j <= n; ++j) {
                f[j - 1].clear();
                for (int i = j; i <= n; ++i) {
                    for (int k = 0; k < f[i].size(); ++k)
                        f[i][k] += ')';
                    for (int k = 0; k < f[i - 1].size(); ++k)
                        f[i].push_back(f[i - 1][k] + '(');
                }
            }
            return f[n];
        }
    };
    

Log in to reply
 

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