Leetcode 118. 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]
]

分析

很简单的二维数组,杨辉三角,上一行的两数相加的和放在下一行。

/**
 * Return an array of arrays.
 * The sizes of the arrays are returned as *columnSizes array.
 * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
 */
int** generate(int numRows, int** columnSizes) {
    int **ans=(int **)malloc(sizeof(int*)*numRows);
    *columnSizes=(int*)malloc(sizeof(int)*numRows);
    for(int i=0;i<numRows;i++)
    {
        ans[i]=(int*)malloc(sizeof(int)*(i+1));
        (*columnSizes)[i]=(i+1);
        ans[i][0]=1;
        for(int j=1;j<i;j++)
            ans[i][j]=ans[i-1][j]+ans[i-1][j-1];
        ans[i][i]=1;
    }
    return ans;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容