首页 > 编程语言 > 详细

leetcode 22. 括号生成 java

时间:2019-09-25 17:28:37      阅读:84      评论:0      收藏:0      [点我收藏+]

题目:

给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。

例如,给出 n = 3,生成结果为:

[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]

解题:

class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList<>();
        return  st(n,n,res,"");
    }

    public static List<String> st(int l,int r, List<String> res, String stemp){
        if(l == 0 && r == 0)
            res.add(stemp);
        if(l > 0)
        {
            st(l - 1, r, res, stemp + "(");
        }
        if( r > 0 && r > l) //  ) 必须匹配之前的 (
            st( l, r-1, res, stemp + ")");
        return res;
    }
}

 

leetcode 22. 括号生成 java

原文:https://www.cnblogs.com/yanhowever/p/11585791.html

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