码迷,mamicode.com
首页 > 其他好文 > 详细

22. Generate Parentheses

时间:2016-03-01 00:43:39      阅读:150      评论: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:

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

AC代码:

class Solution(object):
    def generateParenthesis(self, n):
        if n < 1: return [‘‘]
        def backtracing(left, right, current, ret_list):
            if left > 0:
                backtracing(left - 1, right, current + (, ret_list)
            if right > 0:
                if left == right: return
                backtracing(left, right - 1, current + ), ret_list)
            else:
                ret_list.append(current)
        ret_list = []
        backtracing(n, n, ‘‘, ret_list)
        return ret_list

用递归,找准递归出口即可。注意left==right的条件。

22. Generate Parentheses

标签:

原文地址:http://www.cnblogs.com/zhuifengjingling/p/5229422.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!