22. 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:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

 

思路:向string 中插入( 和 ),每插入一个就减1。 那么如何保证这个combination 是正确的呢?

  1. 插入数量不超过n

  2. 可以插入 ) 的前提是 ( 的数量大于 )

所以就得到了递归的两个条件。

 1 class Solution(object):
 2     def generateParenthesis(self, n):
 3         """
 4         :type n: int
 5         :rtype: List[str]
 6         """
 7         res = []
 8         def help(s,left,right):
 9             if(left==0 and right==0):
10                 res.append(s[:])
11                 return 
12             if left>0:
13                 help(s+'(',left-1,right)
14             if right>left:
15                 help(s+')',left,right-1)
16         help('',n,n)
17         return res
原文地址:https://www.cnblogs.com/zle1992/p/8908390.html