解题思路:
在左括号数大于等于右括号数的前提下,逐渐增加 左右括号的数量,直到左括号数达到所需排列的括号数即可
package Algorithms;
public class Bracket {
static int result = 0;
public static void main(String[] args) {
int n = 5;
bracket(0,0,n);
System.out.println("有"+result+"种排列方式");
}
private static void bracket(int left, int right, int n) {
//只要左括号达到n,且大于右括号数,就能说明这是一种排列方式
if(left == n){
result++;
return;
}
//先使左括号数达到最大数,然后逐渐减少左括号数,在left>right的条件下逐渐增加右、左括号
bracket(left+1, right, n);
if(left>right){
bracket(left, right+1, n);
}
}
}