0
点赞
收藏
分享

微信扫一扫

LeetCode22:括号生成

林肯公园_97cc 2022-04-30 阅读 40
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 );
        }
    }
}
举报

相关推荐

0 条评论