TreeviewCopyright © aleen42 all right reserved, powered by aleen42
22. 括号生成
https://leetcode-cn.com/problems/generate-parentheses/
Java
class Solution {
List<String> result = new ArrayList<>();
public List<String> generateParenthesis(int n) {
dfs(n, n, "");
return result;
}
private void dfs(int left, int right, String str) {
if(left == 0 && right == 0) {
result.add(str);
return;
}
if(left > 0) {
dfs(left - 1, right, str + "(");
}
if(right > left) {
dfs(left, right - 1, str + ")");
}
}
}
Python
'''
Author: Goog Tech
Date: 2020-10-27 16:14:18
LastEditTime: 2020-10-27 16:15:08
Description: https://leetcode-cn.com/problems/generate-parentheses/
FilePath: \leetcode-googtech\#22. Generate Parentheses\Solution.py
WebSite: https://algorithm.show/
Reference: https://leetcode-cn.com/problems/generate-parentheses/solution/hui-su-suan-fa-by-liweiwei1419/
'''
class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
result, string = [], ''
def dfs(left, right, string):
if left == 0 and right == 0:
result.append(string)
return
if right < left: return
if left > 0: dfs(left - 1, right, string + '(')
if right > 0: dfs(left, right - 1, string + ')')
dfs(n, n , string)
return result