首页 > 代码库 > Pascal's Triangle

Pascal's Triangle

Given numRows, generate the first numRows of Pascal‘s triangle.

For example, given numRows = 5,
Return

[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

#include<stdio.h>
#include<stdlib.h>

int **generate(int numRows){
    int **p=(int **)malloc(sizeof(int *)*numRows);
    int i,j;
    for(i=0;i<numRows;i++){
        p[i]=(int *)malloc((i+1)*sizeof(int));
        p[i][0]=p[i][i]=1;
        for(j=1;j<i;j++) p[i][j]=p[i-1][j-1]+p[i-1][j];
    }
    return p;
}

void main()
{
    int n=4,i,j;
    int **p=generate(n);
    for(i=0;i<n;i++){
        for(j=0;j<=i;j++){
            printf("%d",p[i][j]);
        }
        printf("\n");
    }
}


Pascal's Triangle