1 从组合数的定义可以知道。C(n, m) = C(n-1, m) + C(n-1, m-1); 2 所以,根据这个公式可以递归的求得组合数,代码如下: 3 4 long long C(int n, int m) { 5 if(m == 0 || n == 0 || n == 1 || m == n) return 1; 6 if(aug[n][m] != 0) return aug[n][m]; 7 8 aug[n-1][m] = C(n-1, m); 9 aug[n-1][m-1] = C(n-1, m-1); 10 11 return aug[n-1][m] + aug[n-1][m-1]; 12 }
1 非递归的写法: 2 3 long long C(int n, int m) { 4 int i, j; 5 for(i = 0; i <= m; i++) 6 aug[0][i] = aug[1][i] = 1; 7 for(i = 0; i <= n; i++) 8 aug[i][0] = 1; 9 for(i = 0; i <= m; i++) {aug[i][i] = 1;} 10 for(i = 1; i <= n; i++) { 11 for(j = 1; j <= m; j++) { 12 if(i != j) 13 aug[i][j] = aug[i-1][j] + aug[i-1][j-1]; 14 } 15 } 16 return aug[n][m]; 17 }