Python3解法:(参考答案)
思路1:回溯
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
curr = ""
res = []
def dfs(curr, left, right):
if left==0 and right==0:
res.append(curr)
return
if right<left:
return
if left>0:
dfs(curr+"(", left-1, right)
if right>0:
dfs(curr+")", left, right-1)
dfs(curr, n, n)
return res
思路2:动态规划
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
if n == 0:
return []
dp = [None for _ in range(n + 1)]
dp[0] = [""]
for i in range(1, n + 1):
cur = []
for j in range(i):
left = dp[j]
right = dp[i - j - 1]
for s1 in left:
for s2 in right:
cur.append("(" + s1 + ")" + s2)
dp[i] = cur
return dp[n]
C++解法:思路参考Python
class Solution {
public:
vector<string> result;
void dfs(string curr, int left, int right){
if (left==0 && right==0){
result.push_back(curr);
return;
}
if (right<left){
return;
}
if (left>0){
dfs(curr+"(", left-1, right);
}
if (right>0){
dfs(curr+")", left, right-1);
}
}
vector<string> generateParenthesis(int n) {
string curr = "";
dfs(curr, n, n);
return result;
}
};
思路2:动态规划(代码参考)
class Solution {
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++) {
for (int j = 0; j <i; j++) {
for (string p : dp[j])
for (string q : dp[i - j - 1]) {
string str = "(" + p + ")" + q;
dp[i].push_back(str);
}
}
}
return dp[n];
}
};