22. 括号生成

https://leetcode-cn.com/problems/generate-parentheses/

image.png

(图片来源https://leetcode-cn.com/problems/generate-parentheses/

日期 是否一次通过 comment
2020-03-23 0

/** 遍历 */
 public List generateParenthesis(int nPar) {
        List res = new ArrayList<>();

        genPar(res, "", 0, 0, nPar);

        return res;
    }

    private void genPar(List res, String midStr, int open, int close, int nPair) {
        if(midStr.length() == 2*nPair) {
            res.add(midStr);
            return;
        }

        if(open < nPair) {
            genPar(res, midStr+"(", open+1, close, nPair);
        }

        if(close < open) {
            genPar(res, midStr+")", open, close+1, nPair);
        }

    }

你可能感兴趣的:(22. 括号生成)