題目
原題頁面:https://leetcode.com/problems/generate-parentheses/
題目型別:Backtracking, String
難度評價:Medium
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
分析
常見的遞歸回溯題目,要求左右括號匹配出現。只要符合一個規則即可認為是匹配:從左往右遍歷時,左括號的數量>=右括號的數量。因此,每一層遞迴時,有兩種分支選擇:新增左括號,或者新增右括號。某一個分支能否繼續,取決於是否符合上述規則。而判斷分支的結束,就在於n個左括號和n個右括號都已經出現完。
程式碼中的left_count是記錄當前層次遞迴時已經出現過的左括號數,left_remain是記錄可供“消耗”的左括號數,即當前左括號數減去右括號數。Python的兩個列表相加,表示將兩個子列表合併成一個列表,如[1, 2] + [3] = [1, 2, 3]。
程式碼
1 | class Solution: |
本文地址:https://xnerv.wang/zh-tw/leetcode-generate-parentheses/
