class Solution {
List<String> res = new ArrayList<>();
String nowStr = "";
public List<String> generateParenthesis(int n) {
dfs(0, 0, n);
return res;
}
// open已有左括号,close已有右括号
public void dfs(int open, int close, int n) {
if (nowStr.length() == 2*n){
res.add(nowStr);
}
if (open < n){
nowStr = nowStr + "(";
dfs(open+1, close, n);
nowStr = nowStr.substring(0, nowStr.length() -1 );
}
if (close < open){
nowStr = nowStr + ")";
dfs(open, close+1, n);
nowStr = nowStr.substring(0, nowStr.length() -1 );
}
}
}
LeetCode22:括号生成
于 2022-04-30 10:55:41 首次发布