当前位置:网站首页>【leetcode】22. bracket-generating

【leetcode】22. bracket-generating

2022-07-06 03:56:00 Chinese fir sauce_

subject :

22.  Bracket generation 
 Numbers  n  Represents the logarithm of the generated bracket , Please design a function , Used to be able to generate all possible and   Effective   Bracket combination .

 Example  1:

 Input :n = 3
 Output :["((()))","(()())","(())()","()(())","()()()"]
 Example  2:

 Input :n = 1
 Output :["()"]
 
 Tips :

1 <= n <= 8

Depth-first traversal :

class Solution {
    
    List<String> ans;
    public List<String> generateParenthesis(int n) {
    
      ans = new ArrayList<>();
      search(0,0,n,0,"");
        return ans;
    }
    void search(int ln,int rn,int n,int len,String cur){
    
        if(len == n * 2){
    
            ans.add(new String(cur));
            return;
        }
        //  The number of left parentheses is less than n
        if(ln < n){
    
            search(ln+1,rn,n,len+1,cur+"(");
        }
        //  The number of right parentheses is less than that of left parentheses 
        if(rn < ln){
    
            search(ln,rn+1,n,len+1,cur+")");
        }
    }
}
原网站

版权声明
本文为[Chinese fir sauce_]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202132256251202.html