算法: 递归生成成对的括号22. Generate Parentheses

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. The idea is to add ‘)’ only after valid ‘(’
  2. We use two integer variables left & right to see how many ‘(’ & ‘)’ are in the current string
  3. If left < n then we can add ‘(’ to the current string
  4. If right < left then we can add ‘)’ to the current string
    在这里插入图片描述
class Solution:
    def generateParenthesis(self, n: int) -> List[str]:
        res = []
        res_len = n * 2
        def dfs(s, left, right):
            if len(s) == res_len:
                res.append(s)
                return
            if left < n:
                dfs(s+'(', left+1, right)
            
            if left > right:
                dfs(s+')', left, right+1)
        
        dfs('', 0, 0)
        return res
            

给定代码的时间复杂度为 O(2^N),其中 N 是 n 的值。

代码使用深度优先搜索(DFS)方法生成所有有效的括号组合。它在每个位置上递归地探索所有可能的选择,直到形成一个有效的括号组合。

在 dfs 函数中,当字符串 s 的长度等于 res_len 时达到基本情况,其中 res_len 等于 n * 2。这表示已经形成了一个有效的括号组合,并将其附加到 res 列表中。

dfs 函数中的递归调用基于两个条件:

  1.  如果左括号的数量(left)小于 n,则递归调用 dfs(s+'(', left+1, right)。这表示选择将左括号 '(' 添加到字符串 s 中,并递增 left 计数。
    
  2.  如果 left 计数大于 right 计数,则递归调用 dfs(s+')', left, right+1)。这表示选择将右括号 ')' 添加到字符串 s 中,并递增 right 计数。
    

这两个递归调用继续按照 DFS 方法进行所有可能的选择的探索。
由于结果字符串中的每个位置都有两个选择(左括号或右括号),因此递归调用的总次数将为 2^N,其中 N 是 n 的值。
因此,代码的时间复杂度为 O(2^N),因为递归调用的次数和结果列表 res 的大小随着 n 的增长而指数级增加。

猜你喜欢

转载自blog.csdn.net/zgpeace/article/details/131565743
今日推荐