杨辉三角

                          1
                         1   1
                       1   2   1
                     1   3   3   1
                   1   4   6   4   1
                 1   5   10  10  5   1
               1   6   15  20  15  6   1
             1   7   21  35  35  21  7   1   
           1   8   28  56  70  56  28  8   1   
         1   9   36  84  126 126 84  36  9   1   
       1   10  45  120 210 252 210 120 45  10  1   
     1   11  55  165 330 462 462 330 165 55  11  1    
   1   12  66  220 495 792 924 792 495 220 66  12  1
  • 前提:端点的数为1.
  • 每个数等于它上方两数之和。
  • 每行数字左右对称,由1开始逐渐变大。
  • 第n行的数字有n项。
  • 第n行数字和为2n-1。
  • 每个数字等于上一行的左右两个数字之和。可用此性质写出整个杨辉三角。即第n+1行的第i个数等于第n行的第i-1个数和第i个数之和,这也是组合数的性质之一。
1
1    1
1    2    1
1    3    3    1
1    4    6    4    1
1    5    10   10   5    1
1    6    15   20   15   6    1
1    7    21   35   35   21   7    1  
1    8    28   56   70   56   28   8    1  
1    9    36   84   126  126  84   36   9    1  
1    10   45   120  210  252  210  120  45   10   1  
1    11   55   165  330  462  462  330  165  55   11   1 1    12   66   220  495  792  924  792  495  220  66   12   1
其实质是二项式(a+b)的n次方展开后各项的系数排成的三角形,它的特点是左右两边全是1,从第二行起,中间的每一个数是上一行里相邻两个数之和。
#include <stdio.h>
#include <stdlib.h>

const int length = 10;  // 定义杨辉三角的大小

int main(void)
{
    int nums[length][length];
    int i, j;
    /*计算杨辉三角*/ 
    for(i=0; i<length; i++)
    {
        nums[i][0] = 1;
        nums[i][i] = 1;
        for(j=1; j<i; j++)
            nums[i][j] = nums[i-1][j-1] + nums[i-1][j];
    }

    /*打印输出*/ 
    for(i=0; i<length; i++)
    {
        for(j=0; j<length-i-1; j++)
            printf("   ");
        for(j=0; j<=i; j++)
            printf("%-5d ", nums[i][j]);
        putchar('
');
    }
}
 
原文地址:https://www.cnblogs.com/2228212230qq/p/7886209.html