题目:
题解:
一共有2n个括号,套用递归模板,当左括号和右括号等于n的时候,这层递归返回,注意左括号次数小于n拼接左括号,右括号需要小于左括号的次数才能拼接右括号。
代码
List<String> ans = new ArrayList<>();
public List<String> generateParenthesis(int n) {
if (n == 0) {
return ans;
}
int left = 0;
int right = 0;
dfs("", left, right, n);
return ans;
}
public void dfs(String s, int left, int right, int n) {
if (left == n && right == n) {
ans.add(s);
return;
}
if (left < n) {
dfs(s + "(", left + 1, right, n);
}
if (right < left) {
dfs(s + ")", left, right + 1, n);
}
}
备注
本文正在参与「掘金 2021 春招闯关活动」, 点击查看。