forked from yingl/LintCodeInPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate_parentheses.py
More file actions
21 lines (19 loc) · 908 Bytes
/
generate_parentheses.py
File metadata and controls
21 lines (19 loc) · 908 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# -*- coding: utf-8 -*-
class Solution:
# @param {int} n n pairs
# @return {string[]} All combinations of well-formed parentheses
def generateParenthesis(self, n):
# Write your code here
self.limit = n
self.ret = []
self._generateParenthesis('', 0, 0)
return self.ret
def _generateParenthesis(self, comb, left_pars, right_pars):
if (left_pars == self.limit) and (right_pars == self.limit):
if self.limit > 0: # 处理n等于0的特殊情况
self.ret.append(comb)
return
if left_pars < self.limit: # 左括号数目必须小于等于n
self._generateParenthesis(comb + '(', left_pars + 1, right_pars)
if right_pars < left_pars: # 未完成的组合,右括号数目必须小于等于左括号。
self._generateParenthesis(comb + ')', left_pars, right_pars + 1)