22. Title brackets generated leetcode

topic

N represents the number of generation is given in parentheses, you write a function, it is possible to generate all possible combinations of brackets and effective.

Examples

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

General idea

Here Insert Picture Description
Photos from the network

Code

	public List<String> generateParenthesis(int n) {
		//结果集
        List<String> re=new ArrayList<String>();
        
        //n为0直接返回
        if(n==0) return re;
        
        //加入初始字符串
        AddBracket(re, "", n, n);
        
        
        return re;
    }
	
	//re是结果集,a是左括号剩余个数,b是右括号剩余个数
	public void AddBracket(List<String> re,String str,int a,int b){
		if(a==0 && b==0){
			re.add(str);
			return;
		}
		
		if(a>b){
			return;
		}
		
		if(a>0){
			AddBracket(re, str+"(", a-1, b);
		}
		
		if(b>0){
			AddBracket(re, str+")", a, b-1);
		}
	}
Published 15 original articles · won praise 0 · Views 183

Guess you like

Origin blog.csdn.net/qq_36360463/article/details/103978066