常规写法,非递归。这里测试要从第二行开始输出。
#include <iostream> using namespace std; int Triangle[1000][1000]; void getAngle(int n){ Triangle[1][1] = 1; Triangle[2][1] = 1; Triangle[2][2] = 1; for (int i = 3; i <= n; i++){ for (int j = 1; j <= i; j++){ Triangle[i][j] = Triangle[i - 1][j - 1] + Triangle[i - 1][j]; } } for (int i = 2; i <= n; i++){ for (int j = 1; j <= i; j++){ if (j == i) cout << Triangle[i][j]; else cout << Triangle[i][j] << " "; } cout << endl; } } int main(){ int n; while(cin >> n){ getAngle(n); } return 0; }
递归写法
#include <iostream> using namespace std; int Triangle[1000][1000]; int func(int i, int j){ if(j == 1 || i == j){ return 1; }else{ return func(i-1, j-1) + func(i-1, j); } } int main(){ int n; while(cin >> n){ for(int i = 2; i <= n; i++){ for(int j = 1; j <= i; j++){ if(j == 1){ cout << func(i, j); }else{ cout << " " << func(i, j); } } cout << endl; } } return 0; }