首页 > 编程语言 > 详细

Generate Parentheses (Java)

时间:2019-04-18 12:44:55      阅读:116      评论:0      收藏:0      [点我收藏+]
public List<String> generateParenthesis(int n) {
    ArrayList<String> result = new ArrayList<String>();
    dfs(result, "", n, n);
    return result;
}
/*
left and right represents the remaining number of ( and ) that need to be added. 
When left > right, there are more ")" placed than "(". Such cases are wrong and the method stops. 
*/
public void dfs(ArrayList<String> result, String s, int left, int right){
    if(left > right)
        return;
 
    if(left==0&&right==0){
        result.add(s);
        return;
    }
 
    if(left>0){
        dfs(result, s+"(", left-1, right);
    }
 
    if(right>0){
        dfs(result, s+")", left, right-1);
    }
}

  

Generate Parentheses (Java)

原文:https://www.cnblogs.com/wylwyl/p/10728872.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!