Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 22. Generate Parentheses

Rain Hu

22. Generate Parentheses


一、題目

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

Example 1:

Example 2:

Constraints:


二、分析

三、解題

1. Backtrack

vector<string> generateParenthesis(int n) {
    string path;
    vector<string> res;
    backtrack(n, 0, 0, res, path);
    return res;
}
void backtrack(int n, int left, int right, vector<string>& res, string& path) {
    // terminate
    if (path.length() == 2*n) {
        res.push_back(path);
        return;
    }

    // select
    if (left < n) {
        path.push_back('(');
        backtrack(n, left+1, right, res, path);
        path.pop_back();
    }
    if (right < n && right < left) {
        path.push_back(')');
        backtrack(n, left, right+1, res, path);
        path.pop_back();
    }
}

2. Dynamic Programming

vector<string> generateParenthesis(int n) {
    vector<vector<string>> dp(n+1);
    dp[0] = {""}; 
    for(int i=1;i<=n;i++){
        for(int j=0;j<i;j++){
            vector<string> left = dp[j];
            vector<string> right = dp[i-j-1];
            for(int k=0;k<left.size();k++){
                for(int l=0;l<right.size();l++){
                    dp[i].push_back("(" + left[k] + ")" + right[l]);
                }
            }
        }
    }
    return dp[n];
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 23. Merge k Sorted Lists
Next
[LeetCode] 21. Merge Two Sorted Lists