22. 括號生成 Generate Parentheses
阿新 • • 發佈:2020-12-06
Givenn
pairs of parentheses, write a function togenerate all combinations of well-formed parentheses.
Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
方法一:
遞迴+遍歷。
申請2n長度的字元陣列
每位分別賦值為左右括號,當長度為2n時判斷是否合法
public List<String> generateParenthesis(int n) { List<String> ans = newArrayList<>(); generate(ans, new char[2 * n ], 0); return ans; } public void generate(List<String> ans, char[] cur, int n){ if( n == cur.length) { if(valid(cur)){ ans.add(new String(cur)); } return; }else{ cur[n] = '('; generate(ans, cur, n + 1); cur[n] = ')'; generate(ans , cur, n + 1); } } public boolean valid(char []cur){ int balance = 0; for(char c: cur){ if(c == '('){ balance+= 1; }else{ balance -= 1; } if(balance < 0) return false; } return balance == 0; }
方法二:
回溯法,新增左括號的規則是左括號數量小於n。新增右括號的規則是右括號小於左括號。
當然方法一也可以增加新增括號規則。
public List<String> generateParenthesis(int n) { List<String> ans = new ArrayList<>(); backtrack(ans, new StringBuilder(), 0 ,0 , n); return ans; } public void backtrack(List<String> ans, StringBuilder cur, int left, int right, int max){ if(cur.length() == 2 * max){ ans.add(cur.toString()); return; } if (left < max){ cur.append('('); backtrack(ans, cur, left + 1, right, max); cur.deleteCharAt(cur.length() - 1); } if( right < left ){ cur.append(')'); backtrack(ans, cur, left, right + 1, max); cur.deleteCharAt(cur.length() - 1); } }
參考連結:
https://leetcode.com/problems/generate-parentheses/
https://leetcode-cn.com/problems/generate-parentheses/