[Leetcode][Python]22: Generate Parentheses

本文介绍了一种解决LeetCode上第22题“括号生成”的算法,该题要求给定n对括号,生成所有可能的合法括号组合。通过递归方法,使用left和right变量跟踪剩余的左右括号数量,确保生成的组合是合法的。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# -*- coding: utf8 -*-
'''
__author__ = 'dabay.wang@gmail.com'

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===
递归。
用left和right来记录剩余的左右括号数量。
如果都不剩余了,把结果放入要返回的列表中。
如果剩下的左括号比右括号多,说明不是合法的组合,返回。
'''

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)

转载于:https://www.cnblogs.com/Dabay/p/4254099.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值