简繁EN

LeetCodeNo. 003

[LeetCode with Python] 22. Generate Parentheses

Contents

Problem

Problem page: https://leetcode.com/problems/generate-parentheses/
Topics: Backtracking, String
Difficulty: 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:

"((()))", "(()())", "(())()", "()(())", "()()()"


Analysis

A common recursive backtracking problem, where opening and closing parentheses have to match. I only need one rule to check for a match: as I scan from left to right, the number of opening parentheses so far must be >= the number of closing parentheses. So at each level of recursion, I have two choices: add an opening parenthesis or add a closing parenthesis, but I can only continue down a branch if that choice keeps the counts within the rule. A branch ends once I've added n of each kind.
In the code, left_count tracks how many opening parentheses I've added so far. left_remain is the opening count minus the closing count, which gives me the number of opening parentheses I can still "use up". Adding two lists in Python joins them into one list, as in [1, 2] + [3] = [1, 2, 3].


Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution:

def doGenerateParenthesis(self, n, left_count, left_remain, prefix):

# only one out-point: the string has been finished.
if n == left_count and 0 == left_remain:
return [ prefix ]

left_list = [ ]
right_list = [ ]
if left_count < n:
left_list = self.doGenerateParenthesis(n, left_count + 1, left_remain + 1, prefix + "(")
if left_remain > 0:
right_list = self.doGenerateParenthesis(n, left_count, left_remain - 1, prefix + ")")

return left_list + right_list

# @param an integer
# @return a list of string
def generateParenthesis(self, n):
if 0 == n:
return [ ]
else:
list = self.doGenerateParenthesis(n, 0, 0, "")
return list

Article link: https://xnerv.wang/en/leetcode-generate-parentheses/