iT邦幫忙

2025 iThome 鐵人賽

DAY 22
0
自我挑戰組

leetcode系列 第 22

leetcode 22. Generate Parentheses

  • 分享至 

  • xImage
  •  

題目:
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
給定n一對括號,寫一個函數來產生所有格式正確的括號組合。
給定一個整數 n,請生成所有可能且 有效的括號組合。

例如:
輸入: n = 3
輸出: ["((()))","(()())","(())()","()(())","()()()"]

https://ithelp.ithome.com.tw/upload/images/20251006/20169340mUTMX0PmoF.png

解題思路

這是一道典型的 回溯 (Backtracking) 題目。

有效括號條件

左括號數量 ≤ n

右括號數量 ≤ 左括號數量

回溯框架

使用遞迴方法 backtrack(curr, left, right):

curr:當前字串

left:已用的左括號數量

right:已用的右括號數量

當 curr 長度 = 2n → 加入結果集。

如果 left < n → 可以加入 '('。

如果 right < left → 可以加入 ')'。

剪枝

保證隨時 right <= left,避免無效組合。


上一篇
leetcode 21. Merge Two Sorted Lists
系列文
leetcode22
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言