leetcode.22. 括号生成

数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。

 

示例 1:

输入:n = 3
输出:["((()))","(()())","(())()","()(())","()()()"]
示例 2:

输入:n = 1
输出:["()"]
 

提示:

1 <= n <= 8

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/generate-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 
class Solution {
    public List<String> generateParenthesis(int n) {
      List<String>res=new ArrayList();
      generate(res,"",0,0,n);
      return res;
    }
    public void generate(List<String> res,String ans,int count1,int count2,int n){
        if(count1>n||count2>n)return;
        if(count1==n&&count2==n)res.add(ans);
        if(count1>=count2){
            String ans1=new String(ans);
            generate(res,ans+"(",count1+1,count2,n);
            generate(res,ans+")",count1,count2+1,n);
        }
    }
}
posted @ 2022-07-21 19:07  开源遗迹  阅读(20)  评论(0)    收藏  举报