【LeetCode with Python】 Generate Parentheses
来源:互联网 发布:高薪网络销售招聘 编辑:程序博客网 时间:2024/05/02 00:24
博客域名:http://www.xnerv.wang
原题地址:https://oj.leetcode.com/problems/generate-parentheses/
题目类型:递归,回溯
难度评价:★★
本文地址:http://blog.csdn.net/nerv3x3/article/details/2920102
常见的递归回溯题目,要求左右括号匹配出现。只要符合一个规则即可认为是匹配:从左往右遍历时,左括号的数量>=右括号的数量。因此,每一层递归时,有两种分支选择:添加左括号,或者添加右括号。某一个分支能否继续,取决于是否符合上述规则。
代码中的left_count是记录当前层次递归时已经出现过的左括号数,left_remain是记录可供“消耗”的左括号数,即当前左括号数减去右括号数。Python的两个列表相加,表示将两个子列表合并成一个列表,如[1, 2] + [3] = [1, 2, 3]。
原题地址:https://oj.leetcode.com/problems/generate-parentheses/
题目类型:递归,回溯
难度评价:★★
本文地址:http://blog.csdn.net/nerv3x3/article/details/2920102
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:
"((()))", "(()())", "(())()", "()(())", "()()()"
常见的递归回溯题目,要求左右括号匹配出现。只要符合一个规则即可认为是匹配:从左往右遍历时,左括号的数量>=右括号的数量。因此,每一层递归时,有两种分支选择:添加左括号,或者添加右括号。某一个分支能否继续,取决于是否符合上述规则。
代码中的left_count是记录当前层次递归时已经出现过的左括号数,left_remain是记录可供“消耗”的左括号数,即当前左括号数减去右括号数。Python的两个列表相加,表示将两个子列表合并成一个列表,如[1, 2] + [3] = [1, 2, 3]。
class Solution: def doGenerateParenthesis(self, n, left_count, left_remain, prefix): # only one out-point: the string has been finished. if n == left_count and 0 == left_remain: return [ prefix ] left_list = [ ] right_list = [ ] if left_count < n: left_list = self.doGenerateParenthesis(n, left_count + 1, left_remain + 1, prefix + "(") if left_remain > 0: right_list = self.doGenerateParenthesis(n, left_count, left_remain - 1, prefix + ")") return left_list + right_list # @param an integer # @return a list of string def generateParenthesis(self, n): if 0 == n: return [ ] else: list = self.doGenerateParenthesis(n, 0, 0, "") return list
- 【LeetCode with Python】 Generate Parentheses
- 【LeetCode with Python】 Generate Parentheses .
- 【Leetcode】【python】Generate Parentheses
- 21. Generate Parentheses Leetcode Python
- [leetcode: Python]22. Generate Parentheses
- [python]leetcode(22). Generate Parentheses
- [leetcode]Generate Parentheses 生成圆括号 python实现
- LeetCode--Generate Parentheses(括号组合排列)Python
- 【LeetCode with Python】 Valid Parentheses
- LeetCode: Generate Parentheses
- LeetCode: Generate Parentheses
- [Leetcode] Generate Parentheses
- leetcode 51: Generate Parentheses
- [LeetCode] Generate Parentheses
- Leetcode: Generate Parentheses
- LeetCode Generate Parentheses
- 【leetcode】Generate Parentheses
- [LeetCode]Generate Parentheses
- validateJarFile jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class
- 佛说
- 关于c函数c++函数的调用问题
- Struts2
- 指针详解
- 【LeetCode with Python】 Generate Parentheses
- 数字水印的嵌入与检测 WaterMark 1.0
- log4j:WARN Please initialize the log4j system properly 问题解决
- 【LeetCode with Python】 Best Time to Buy and Sell Stock
- 用带有PTDD Partition Table Doctor的WinPE处理硬盘0磁道损坏问题
- 在ACCESS中,"!"及"."符号之差别为何?
- 用带有PTDD Partition Table Doctor的WinPE修复硬盘主引导记录
- -
- tomcat控制台输出信息时会卡住的原因