hdu2049遞迴問題

XiaohuangTX發表於2024-05-12

解法:從N中選出M個C[n][m],然後乘上錯排公式;f[n]=(n-1)*(f[n-1]+f[n-2]);f[0]=0;f[1]=1;

import java.util.Scanner;

public class hdu2049 {
    public static int C(int a,int b) {
        if (a==b) {
            return 1;
        }else if (b==1) {
            return a;
        }else {
            return C(a-1, b-1)+C(a-1, b);
        }
    }

    public static void main(String[] args) {
        // TODO 自動生成的方法存根
        long[] aa = new long[21];
        aa[1] = 0;
        aa[2] = 1;
        for (int i = 3; i < aa.length; i++) {
            aa[i] =(i-1)*(aa[i-1]+aa[i-2]);
        }        
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        for (int i = 0; i < n; i++) {
            int N = sc.nextInt();
            int M = sc.nextInt();
            System.out.println(C(N,M)*aa[M]);
        }
        sc.close();
    }

}

相關文章