#-*-Coding:utf8-*-
‘‘‘
__author__ = ' [email protected] '
22:generate parentheses
https://oj.leetcode.com/problems/generate-parentheses/
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:
"((()))", "(()())", "(())()", "()(())", "()()()"
===comments by dabay===
Recursion.
Use left and right to record the remaining number of brackets.
If none is left, put the result in the list that you want to return.
If the left parenthesis is more than the closing parenthesis, the description is not a valid combination and is returned.
‘‘‘
Class Solution:
# @param an integer
# @return A list of string
def generateparenthesis (self, N):
Def GenerateParenthesis2 (left, right, string, res):
If left = = 0 and right = = 0:
Res.append (String)
Return
If left > right:
Return
If left > 0:
GenerateParenthesis2 (Left-1, right, String + "(", RES)
If right > 0:
GenerateParenthesis2 (left, right-1, String + ")", RES)
res = []
GENERATEPARENTHESIS2 (n, N, "", RES)
return res
def main ():
Sol = solution ()
Print Sol.generateparenthesis (4)
if __name__ = = ' __main__ ':
Import time
Start = Time.clock ()
Main ()
Print "%s sec"% (Time.clock ()-start)
[Leetcode] [Python]22:generate parentheses