183 统计和生成所有不同的二叉树(进阶)
Table of Contents

ac

前几项为:1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786, 208012

static long rev(int n){
        // 0 处理成 1
        long[] arr = new long[N];
        arr[0] = 1;
        arr[1] = 1;
        arr[2] = 2;
        if(n <= 2){
            return arr[n];
        }
        for(int k=3;k<=n;k++) {
            long sum = 0;
            for (int i = 0; i < k; i++) {
                int leftCnt = i;
                int rightCnt = k - i - 1;
                sum += arr[leftCnt] * arr[rightCnt];
                sum %= mod;
            }
            arr[k] = sum;
        }
        return arr[n];
    }

公式,快速幂

参考: https://cloud.tencent.com/developer/article/1556012

C(n) = C(0) * C(n-1) + C(1) * C(n-2) +  + C(n-2) * C(1) + C(n-1) * C(0)
f(n) = c[2n,n] - c[2n, n+1] = c[2n,n]/(n+1)

f(n+1) = [(4n-2) / (n+1)] * f(n)

参考: https://blog.csdn.net/xiaoming_p/article/details/79644386

(a/b)%M = a*(b的逆元)%M
b关于模数M的逆元 inv[b]=(M - M / b) * inv[M % b] % M;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;

class TreeNode{
    TreeNode left;
    TreeNode right;
    int val;

    public TreeNode(int val) {
        this.val = val;
        left = null;
        right = null;
    }
}

public class Main{
    public static Scanner sc = new Scanner(System.in);

    public static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

    public static int mod=(int)Math.pow(10,9)+7;

    public static int N = 1000001;

    public static void main(String[] args) throws Exception {
        int n = sc.nextInt();
        System.out.print(rev(n));
//        for(int i=1;i<44;i++){
//            System.out.println(i + " " + rev(i));
//        }
    }

    static long rev(int n){
        if(n == 0){
            return 1;
        }
        if(n == 1 || n == 2){
            return n;
        }
        // 0 处理成 1
        long[] arr = new long[n+1];
        arr[0] = 1;
        arr[1] = 1;
        arr[2] = 2;
        //求逆元
        long[] inv = new long[n + 2];
        inv[1] = 1;
        for (int b = 2; b <= n + 1; b++) {
            inv[b] = (mod - mod / b) * inv[mod % b] % mod;
        }
        for(int k=3;k<=n;k++) {
            arr[k] = (4 * k - 2) * inv[k + 1] % mod * arr[k-1] % mod;
        }
        return arr[n];
    }

}
/*
结构
  2  1
 /    \
1      2

7

429

43

4616923
 */