Leetcode 22. Generate Parentheses
2017-04-24 15:22
267 查看
题目:
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:
思路:
用一个标志变量stackNum模拟一个栈中'('的数量,递归生成所需要的序列,若栈空则入左括号,若栈不空则有两种可能分别递归执行,直到左右括号皆用完。
class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
if n<=0:return []
res = []
self.generator(n,n,0,'',res)
return res
def generator(self,n_l,n_r,stackNum,curStr,res):
if n_l<=0 and n_r<=0:
res.append(curStr)
return
if stackNum==0:
self.generator(n_l-1,n_r,stackNum+1,curStr+'(',res)
else:
if n_l>0:
self.generator(n_l-1,n_r,stackNum+1,curStr+'(',res)
if n_r>0:
self.generator(n_l,n_r-1,stackNum-1,curStr+')',res)
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:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
思路:
用一个标志变量stackNum模拟一个栈中'('的数量,递归生成所需要的序列,若栈空则入左括号,若栈不空则有两种可能分别递归执行,直到左右括号皆用完。
class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
if n<=0:return []
res = []
self.generator(n,n,0,'',res)
return res
def generator(self,n_l,n_r,stackNum,curStr,res):
if n_l<=0 and n_r<=0:
res.append(curStr)
return
if stackNum==0:
self.generator(n_l-1,n_r,stackNum+1,curStr+'(',res)
else:
if n_l>0:
self.generator(n_l-1,n_r,stackNum+1,curStr+'(',res)
if n_r>0:
self.generator(n_l,n_r-1,stackNum-1,curStr+')',res)
相关文章推荐
- python写算法题:leetcode: 22. Generate Parentheses
- leetcode-java-22. Generate Parentheses
- DFS leetcode 22. Generate Parentheses
- LeetCode22. Generate Parentheses
- LeetCode 22. Generate Parentheses 解题报告
- LeetCode-22. Generate Parentheses
- LeetCode - 22. Generate Parentheses
- leetcode 22. Generate Parentheses 巧妙的递归形式
- [LeetCode]22. Generate Parentheses
- LeetCode 22. Generate Parentheses
- LeetCode 22. Generate Parentheses 题解 —— Java
- leetcode_22. Generate Parentheses 生成括号,给n对括号,有多少种括号生成方式
- leetcode:22. Generate Parentheses
- 【leetcode】22. Generate Parentheses
- 【LeetCode】22. Generate Parentheses 解题报告
- LeetCodet题解--22. Generate Parentheses(生成n对匹配的括号)
- [leetcode]22. Generate Parentheses
- leetcode 20|22|32. Valid Parentheses 22. Generate Parentheses 32. Longest Valid Parentheses
- [leetCode刷题笔记]22. Generate Parentheses
- leetcode--22. Generate Parentheses