题解 | #括号生成#
括号生成
http://www.nowcoder.com/practice/c9addb265cdf4cdd92c092c655d164ca
1、DFS
import java.util.*;
public class Solution {
/**
*
* @param n int整型
* @return string字符串ArrayList
*/
private ArrayList<String> res;
private int n;
public ArrayList<String> generateParenthesis (int n) {
// write code here
this.n = n;
this.res = new ArrayList<>();
dfs("", 0, 0);
return res;
}
private void dfs(String s, int l, int r) {
if (l > n || r > n || r > l) return;
if (l == n && r == n) {
res.add(s);
return;
}
dfs(s + "(", l + 1, r);
dfs(s + ')', l, r + 1);
}
}