1. 程式人生 > 其它 >[leetcode] 22. Generate Parentheses

[leetcode] 22. Generate Parentheses

題目

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

Example 1:

Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]

Example 2:

Input: n = 1
Output: ["()"]

Constraints:

  • 1 <= n <= 8

思路

解法1:使用一個整數序列描述括號,一個整數表示有幾個右括號加一個左括號,例如:0: ( 1: )( 2: ))(

,以此類推。那麼根據1、2、3時的輸出找規律:

1:0 ()
2:00 01 (()) ()()
3:000 001 002 010 011 ((())) (()()) (())() ()(()) ()()()

該過程類似於全排列,不過要求整數序列的總和要小於輸入的值,不然就會出現()))((這樣無法閉合的情況。因此,針對該題可以先有限制的生成全排列的整數序列,然後再根據整數序列生成對應的括號。

解法2:dfs

程式碼

python版本:

class Solution:
    def generateParenthesis(self, n: int) -> List[str]:
        def generate(nums):
            cnt=0
            res=''
            for i in nums:
                res+=i*')'+'('
                cnt+=i
            res+=(len(nums)-cnt)*')'
            return res
        res=[[0]]
        for i in range(1,n):
            res=[r+[j] for r in res for j in range(i+1-sum(r))]
        res=[generate(r) for r in res]
        return res

# dfs
class Solution:
    def generateParenthesis(self, n: int) -> List[str]:
        res = []

        def dfs(now, l, r):
            if l:
                dfs(now+'(', l-1, r)
            if l < r:
                dfs(now+')', l, r-1)
            if not (l or r):
                res.append(now)
        dfs('', n, n)
        return res