您的位置:首页 > 其它

Generate Parentheses

2015-06-02 00:08 197 查看
dfs 的一个关键是termination condition

public class Solution {
public ArrayList<String> generateParenthesis(int n) {
ArrayList<String> res = new ArrayList<String>();
if(n<1) return res;
dfs(n,n,res,new String());
return res;
}
private void dfs(int nl, int nr,ArrayList<String> res, String item){
if(nr<nl) return; // nr>nl not working!!!
if(nr==0 && nl==0) res.add(item);

if(nl>0)
dfs(nl-1, nr, res, item+'(');
if(nr>0)
dfs(nl, nr-1, res, item+')');
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: