#include <iomanip> #include <iostream> using namespace std; int main() { int n, k; cout << "求C(n,k),请输入n和k(k <= n):"; cin >> n >> k; int **p; p = new int*[n + 1]; for (int i = 0; i <= n; i++) p[i] = new int[k + 1]; for (int i = 0; i <= n; i++) for (int j = 0; j <= k; j++) p[i][j] = 0; for (int i = 0; i <= n; i++) p[i][0] = 1; // C(n,0) = 0 for (int i = 0; i <= k; i++) p[i][i] = 1; // C(n,n) = 1 for (int i = 2; i <= n; i++) for (int j = 1; j < (i > k ? k + 1 : i); j++) p[i][j] = p[i - 1][j - 1] + p[i - 1][j]; //cout.flags(ios::right); // 输出对齐 for (int i = 0; i <= n; i++) { for (int j = 0; j <= k; j++) cout << setw(5) << p[i][j] << ' '; cout << endl; } // 销毁空间 for (int i = 0; i <= n; i++) delete[] p[i]; delete[] p; return 0; }
原文地址:http://blog.csdn.net/nestler/article/details/29609089