从组合数的定义可以知道。C(n, m) = C(n-1, m) + C(n-1, m-1);
所以,根据这个公式可以递归的求得组合数,代码如下:
long long C(int n, int m) {
if(m == 0 || n == 0 || n == 1 || m == n) return 1;
if(aug[n][m] != 0) return aug[n][m];
aug[n-1][m] = C(n-1, m);
aug[n-1][m-1] = C(n-1, m-1);
return aug[n-1][m] + aug[n-1][m-1];
}
非递归的写法:
long long C(int n, int m) {
int i, j;
for(i = 0; i <= m; i++)
aug[0][i] = aug[1][i] = 1;
for(i = 0; i <= n; i++)
aug[i][0] = 1;
for(i = 0; i <= m; i++) {aug[i][i] = 1;}
for(i = 1; i <= n; i++) {
for(j = 1; j <= m; j++) {
if(i != j)
aug[i][j] = aug[i-1][j] + aug[i-1][j-1];
}
}
return aug[n][m];
}