We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
https://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:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
两种思路,一种是递归,一种是动态规划
[ ')' * open ]
['('+x for x in generateParenthesis(n-1, 1)]
[')'+x for x in self.generateParenthesis(n, open-1)]
['('+x for x in self.generateParenthesis(n-1, open+1)]
()
'(' + parenthesis(0) + ')' + parenthesis(n-1)
'(' + parenthesis(1) + ')' + parenthesis(n-2)
''
'(' + parenthesis(n-1) + ')' + parenthesis(0)
递归思路(直接复制别人的代码)
class Solution: def generateParenthesis(self, n, open=0): if n == 0: return [')'*open] if open == 0: return ['('+x for x in self.generateParenthesis(n-1, 1)] else: return [')'+x for x in self.generateParenthesis(n, open-1)] + ['('+x for x in self.generateParenthesis(n-1, open+1)]
动态规划(更容易理解,也是复制别人的代码)
# https://discuss.leetcode.com/topic/28374/clean-python-dp-solution class Solution(object): def generateParenthesis(self, n): """ :type n: int :rtype: List[str] """ dp = [[] for i in range(n + 1)] dp[0].append('') for i in range(n + 1): for j in range(i): dp[i] += ['(' + x + ')' + y for x in dp[j] for y in dp[i - j - 1]] return dp[n]
The text was updated successfully, but these errors were encountered:
#4 20170731
Sorry, something went wrong.
No branches or pull requests
问题
https://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:
思路
两种思路,一种是递归,一种是动态规划
[ ')' * open ]
['('+x for x in generateParenthesis(n-1, 1)]
,就是对所有『n-1个闭合括号对&1个右括号』的组合,都在最左侧加一个左括号[')'+x for x in self.generateParenthesis(n, open-1)]
,『n个闭合括号+ n-1个右括号』加一个最左侧的右括号['('+x for x in self.generateParenthesis(n-1, open+1)]
,『n-1个闭合括号 + n +1 个右括号』加一个最左侧的左括号()
'(' + parenthesis(0) + ')' + parenthesis(n-1)
'(' + parenthesis(1) + ')' + parenthesis(n-2)
''
'(' + parenthesis(n-1) + ')' + parenthesis(0)
解答
递归思路(直接复制别人的代码)
动态规划(更容易理解,也是复制别人的代码)
The text was updated successfully, but these errors were encountered: