首页 > 其他 > 详细

22. Generate Parentheses(回溯)

时间:2018-04-22 17:42:10      阅读:197      评论:0      收藏:0      [点我收藏+]
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

 

22. Generate Parentheses(回溯)

原文:https://www.cnblogs.com/zle1992/p/8908390.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!