文章目录
- 1. 题目
- 2. 解题
- 2.1 暴力回溯
- 2.2 DP
1. 题目
给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。
例如,给出 n = 3,生成结果为:["((()))","(()())","(())()","()(())","()()()"
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/generate-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2. 解题
2.1 暴力回溯
- 利用栈检查是否有效
class Solution {
public:vector<string> generateParenthesis(int n) {stack<char> stk;vector<string> ans;string str;int k = 2*n;bt(stk,k,0,str,ans);return ans;}void bt(stack<char> stk, int &k, int i, string str, vector<string> &ans){if(i == k){if(stk.empty())ans.push_back(str);return;}stk.push('(');bt(stk,k,i+1,str+"(",ans);stk.pop();if(!stk.empty()){stk.pop();bt(stk,k,i+1,str+")",ans);}}
};
- 用左右括号数量来判断:任何时候,右括号不能大于左括号个数
class Solution {
public:vector<string> generateParenthesis(int n) {vector<string> ans;string str;int k = 2*n;bt(0,0,k,0,str,ans);return ans;}void bt(int L, int R, int &k, int i, string str, vector<string> &ans){if(L < R)return;if(i == k){if(L == R)ans.push_back(str);return;}bt(L+1,R,k,i+1,str+"(",ans);bt(L,R+1,k,i+1,str+")",ans);}
};
class Solution { // 2020.3.27vector<string> ans;int N;vector<char> ch ={'(',')'};
public:vector<string> generateParenthesis(int n) {N = 2*n;string t;dfs(t,0,0,n,0);return ans;}void dfs(string& t, int l, int r, int n, int count){if(l<r || l > n || r > n)return;if(count == N){ans.push_back(t);return;}for(int i = 0; i < 2; ++i){t.push_back(ch[i]);if(i==0) dfs(t,l+1,r,n,count+1);else dfs(t,l,r+1,n,count+1);t.pop_back();}}
};
2.2 DP
另有DP解法,见别人解答
class Solution { //DP
public:vector<string> generateParenthesis(int n) {if (n == 0) return {};if (n == 1) return { "()" };vector<vector<string>> dp(n+1);dp[0] = { "" };dp[1] = { "()" };for (int i = 2; i <= n; i++) { //求dp[i] 在所有dp[0],...dp[i-1]的基础上进行组合for (int j = 0; j <i; j++) {for (string p : dp[j])for (string q : dp[i - j - 1]) { //j对括号的p,+ 1对新括号 + i-j-1对括号的 q = i对括号string str = "(" + p + ")" + q;dp[i].push_back(str);}}}return dp[n];}
};