image.png
(图片来源https://leetcode-cn.com/problems/generate-parentheses/
)
日期 | 是否一次通过 | comment |
---|---|---|
2020-03-23 | 0 |
/** 遍历 */
public List<String> generateParenthesis(int nPar) {
List<String> res = new ArrayList<>();
genPar(res, "", 0, 0, nPar);
return res;
}
private void genPar(List<String> 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);
}
}
网友评论