Algorithm: Recursively generate paired parentheses 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

Depth-first recursive solution, using left and right counters

  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
    insert image description here
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
            

The time complexity of the given code is O(2^N), where N is the value of n.

The code generates all valid parenthesis combinations using a depth-first search (DFS) method. It recursively explores all possible choices at each position until a valid parenthesis combination is formed.

In the dfs function, the base case is reached when the length of the string s is equal to res_len, where res_len is equal to n * 2. This indicates that a valid parenthesis combination has been formed and appended to the res list.

Recursive calls in the dfs function are based on two conditions:

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

These two recursive calls continue the exploration of all possible options following the DFS approach.
Since each position in the resulting string has two choices (opening or closing parenthesis), the total number of recursive calls will be 2^N, where N is the value of n.
Therefore, the time complexity of the code is O(2^N), because the number of recursive calls and the size of the result list res increase exponentially as n grows.

Guess you like

Origin blog.csdn.net/zgpeace/article/details/131565743