題目:
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
給定n一對括號,寫一個函數來產生所有格式正確的括號組合。
給定一個整數 n,請生成所有可能且 有效的括號組合。
例如:
輸入: n = 3
輸出: ["((()))","(()())","(())()","()(())","()()()"]
解題思路
這是一道典型的 回溯 (Backtracking) 題目。
有效括號條件
左括號數量 ≤ n
右括號數量 ≤ 左括號數量
回溯框架
使用遞迴方法 backtrack(curr, left, right):
curr:當前字串
left:已用的左括號數量
right:已用的右括號數量
當 curr 長度 = 2n → 加入結果集。
如果 left < n → 可以加入 '('。
如果 right < left → 可以加入 ')'。
剪枝
保證隨時 right <= left,避免無效組合。