Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.輸入一個正整數n。要求返回一個List<String>,list中包含n組括號全部可能的符合規則的組合。如「(())」就屬於符合規則的組合,「)(()」就屬於不符合規則的組合。code
例如, 輸入 n = 3, 結果集應當是:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]orm
public List<String> generateParenthesis(int n) { List<String> ans = new ArrayList(); backtrack(ans, "", 0, 0, n); return ans; } public void backtrack(List<String> ans, String cur, int open, int close, int max){ if (cur.length() == max * 2) { ans.add(cur); System.out.println(cur); return; } if (open < max) backtrack(ans, cur+"(", open+1, close, max); if (close < open) backtrack(ans, cur+")", open, close+1, max); }