题目连接:https://leetcode-cn.com/problems/generate-parentheses/java
给出 n 表明生成括号的对数,请你写出一个函数,使其可以生成全部可能的而且有效的括号组合。python
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
回溯算法算法
递归过程当中,经过左括号和右括号的个数判断是否还能够组成有效的括号的组合app
关注个人知乎专栏,了解更多的解题技巧!函数
pythoncode
class Solution: def generateParenthesis(self, n: int) -> List[str]: res = [] def helper(left_p, right_p, tmp): if left_p == 0 and right_p == 0: res.append(tmp) return if left_p < 0 or right_p < 0 or left_p > right_p: return helper(left_p-1, right_p, tmp+"(") helper(left_p, right_p-1, tmp+")") helper(n, n, "") return res
java递归
class Solution { public List<String> generateParenthesis(int n) { ArrayList<String> res = new ArrayList<String>(); backtrack(res, "", n, n); return res; } public void backtrack(ArrayList<String> res, String s, int left_p, int right_p) { if (left_p == 0 && right_p == 0) { res.add(s); return; } if (left_p < 0 || right_p < 0 || left_p > right_p) return; backtrack(res,s+"(",left_p-1,right_p); backtrack(res,s+")",left_p,right_p-1); } }