原题链接:22. Generate Parentheses
【思路-Java、Python】 递归实现
采用递归方式,添加左括号的条件是左括号数量小于 n,添加右括号的条件是右括号数小于左括号数:
public class Solution {
public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<String>();
dfs(res, "", n, 0, 0);
return res;
}
public void dfs(List<String> res, String temp, int n, int left, int right) {
if(right == n) {
res.add(temp);
return;
}
if (left < n) dfs(res, temp+"(", n, left+1, right);
if (right < left) dfs(res, temp+")", n, left, right+1);
}
}
8 / 8
test cases passed. Runtime: 2 ms Your runtime beats 26.33% of javasubmissions.
class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
res = []
def dfs(res, n, s, left, right) :
if right == n : res.append(s)
if left < n :
dfs(res, n, s + "(", left+1, right)
if left > right :
dfs(res, n, s + ")", left, right+1)
dfs(res, n, '', 0, 0)
return res
8 / 8
test cases passed. 8 / 8 test cases passed. Your runtime beats 66.46% of pythonsubmissions.