Leetcode 22. Generate Parentheses
题目

解法:backtracking
关键在于,只要保证当前形成的字符串左括号数量大于等于右括号数量,那么一定可以通过后面添加右括号来形成合法的答案。反过来的话,当前的串一定已经非法了
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
def backtracking(comb,left,right):
# if left==right, means one valid combination found
if left==n and right==n:
ans.append(comb)
# if left<n, mean there must be valid combination with adding one more '('
if left<n:
backtracking(comb+'(',left+1,right)
# if right<n and right<left, means there must be valid combination with one more ')'
if right<n and right<left:
backtracking(comb+')',left,right+1)
ans = []
backtracking('(',1,0)
return ans
C++版本
二刷用C++写的答案更直观
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> ans;
backtracking(ans,"",n,n);
return ans;
}
void backtracking(vector<string>& ans,string comb,int left,int right){
// if right bracket remains smaller than left, meaning current comb must be invalid
if(left>right) return;
if(left == 0 && right == 0){
ans.push_back(comb);
}
if(left){
comb.push_back('(');
backtracking(ans,comb,left-1,right);
comb.pop_back();
}
if(right){
comb.push_back(')');
backtracking(ans,comb,left,right-1);
comb.pop_back();
}
}
};
follow up
Leetcode 32. Longest Valid Parentheses
解法:
https://blog.youkuaiyun.com/qq_37821701/article/details/108977055
该博客介绍了如何使用回溯法(backtracking)解决LeetCode第22题——生成括号的Python解法。关键在于保持左括号数量大于等于右括号数量以确保合法性。此外,还提及了C++版本的解决方案,并推荐了一个后续题目LeetCode 32——最长有效括号,提供了相关解法链接。
261

被折叠的 条评论
为什么被折叠?



