【DFS】LeetCode 22. 括号生成
题目链接
思路
使用 DFS
和贪心的思想,如果左括号的数量不够就优先放置左括号,然后再放置右括号。
代码
class Solution {
private List<String> result = new ArrayList<>();
public List<String> generateParenthesis(int n) {
if(n == 0){
return this.result;
}
dfs(new StringBuilder(), 0, 0, n);
return this.result;
}
void dfs(StringBuilder stringBuilder, int left, int right, int n){
if(left == n && right == n){
this.result.add(stringBuilder.toString());
return;
}
if(left < right){
return;
}
if(left < n){
stringBuilder.append("(");
dfs(stringBuilder, left + 1, right, n);
stringBuilder.deleteCharAt(stringBuilder.length() - 1);
}
if(right < n){
stringBuilder.append(")");
dfs(stringBuilder, left, right + 1, n);
stringBuilder.deleteCharAt(stringBuilder.length() - 1);
}
}
}