【LeetCode】22. 生成括號

問題描述

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

給定n對括號,編寫一個函數來生成所有形式良好的括號組合。

比如,給定 n = 3,則輸出結果應爲:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

 

Python 實現

顯然,這種配對問題使用遞歸的方法來實現是最直觀的。根據題目的條件,需要滿足的幾個基本條件是:

  1. 形式良好的組合,必須滿足左括號與右括號之和等於n*2;
  2. 左括號數量不能大於n;
  3. 右括號不能多於左括號。

因此,在未得到最終組合之前,我們可以向字符串內添加 “(” 或者 “)” 。由於向 res 列表添加組合字符串的操作是在最深一層遞歸調用中實現的,所以當向上一級調用返回時,實際上蘊含一個回溯的思想,即回到上一級的狀態,然後執行不同的操作,從而得到其他形式的組合結果。具體代碼實現如下:

class Solution(object):
    def generateParenthesis(self, n):
        """
        :type n: int
        :rtype: List[str]
        """
        
        if not n:
            return None
        res = []
        self.generate(0, 0, n, "", res)
        return res
        
    def generate(self, left, right, n, string, res):
        # Required result.
        if left+right == 2*n:
            res.append(string)
            return
        
        # Recursive Step.
        if left < n:
            self.generate(left+1, right, n, string+"(", res)
        
        if left > right:
            self.generate(left, right+1, n, string+")", res)
    
        

 

鏈接:https://leetcode.com/problems/generate-parentheses/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章