[Leetcode 22]生成括号generate parentheses

题目

给定括号对数n,生成所有可能的标准括号结果*

*指不能)(

https://leetcode.com/problems/generate-parentheses/

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

 

Example 1:

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

Example 2:

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

 

 

思路

dfs,回溯

生成括号的情况:

当前左括号数<总括号对数+((保证生成n对括号)

当前右括号数<左括号数,+)(保证先左括号再右括号)

当前字符串len=括号对数*2,将结果保存到全局list中,return

 

 

代码

 

class Solution {
    List<String> ans=new ArrayList();
    public List<String> generateParenthesis(int n) {
        fun("",0,0,n);
        //用stringbuilder速度会更快
        return ans;
    }
    
    public void fun(String cur,int left,int right,int max){
        if(cur.length()==max*2){
            ans.add(cur);//一对括号 长度*2
            return;
        }
        
        if(left<max)
            fun(cur+"(",left+1,right,max);//左括号开头,他和总对数比
        if(right<left)
            fun(cur+")",left,right+1,max);//右括号必在左括号后(well-formed要求)
    }

}

 

上一篇:解决Alibaba Cloud View打包上传的错误:No goals have been specified for this build


下一篇:[面试题] 等概率生成器