題目連接: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); } }