1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | /**************************************************************** * Description: C++ implementation of yanghuiRriangle. * Author: Alex Li * Date: 2023-06-22 12:20:50 * LastEditTime: 2023-06-22 15:12:09 ****************************************************************/ #include<iostream> #include<iomanip> using namespace std; int main(){ const int n = 15; //二项式次数,实际取最大值14 const int m = 2 * (n-1); //二项式展开后的项数15,因为元素中间要有n-1个间隔,所以需要29个元素,0~28 int arr[n][m] = { 0 }; for (int i =0; i <n; i++){ arr[i][n-i-1] = 1; //生成三角形左边数值为1 arr[i][n+i-1] = 1; //生成三角形右边数值为1 } for (int i = 2; i <n; i++){//i从第二行遍历 for (int j = n - i + 1; j < n-2+i; j = j + 2)//从上一层的两个相邻数值相加得到结果 arr[i][j] = arr[i - 1][j - 1] + arr[i - 1][j + 1]; } for (int i = 0; i < n; i++){//按行遍历 //输出三角形前面的空格 for (int j = 0; j < n - i - 1; j++)cout << " "; //n-i-1是三角形左边,n+i+1是三角形右边,j每次跳二格 for (int j = n - i - 1; j< n+i+1; j = j + 2){ cout << setw(4) << arr[i][j] << " "; } cout << endl; } return 0; } |