# 【LeetCode】22. 括号生成：深度优先搜索，dfs，剪枝，搜索回溯

#### 这道题目可以使用dfs，即深度优先遍历。加上适当的剪枝。可以求解。搜索回溯。

class Solution {
public List<String> generateParenthesis(int n) {
// 这道题目采用深度优先遍历。适当的剪枝。
if (n == 0) return res;
int remainLeft = n;
int remainRight = n;
StringBuffer path = new StringBuffer();
dfs(res, remainLeft, remainRight, path);
return res;
}

private void dfs(List<String> res, int remainLeft, int remainRight, StringBuffer path) {
if (remainLeft == 0 && remainRight == 0) {
return;
}

// 进行遍历
if (remainLeft > 0) {
if ((remainLeft - 1) <= remainRight) {
path.append("(");
remainLeft--;
dfs(res, remainLeft, remainRight, path);
remainLeft++;
path = path.deleteCharAt(path.length() - 1);
}
}
if (remainRight > 0) {
if (remainLeft <= (remainRight - 1)) {
path.append(")");
remainRight--;
dfs(res, remainLeft, remainRight, path);
remainRight++;
path = path.deleteCharAt(path.length() - 1);
}
}
}
}


06-01 69

02-10 507

10-31 435

04-09 15

12-26 54

11-15 23

07-16 184

12-03 129

11-12 63

04-12 16

09-06 219

03-26 57

03-04 66

04-09 18

02-24 1205

04-28 25

04-10 12

04-09 19

04-14 61万+

#### 在中国程序员是青春饭吗？

©️2019 CSDN 皮肤主题: 书香水墨 设计师: CSDN官方博客