美文网首页
Leetcode 118. Pascal's Triangle

Leetcode 118. Pascal's Triangle

作者: persistent100 | 来源:发表于2017-09-02 22:31 被阅读0次

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;
}

相关文章

网友评论

      本文标题:Leetcode 118. Pascal's Triangle

      本文链接:https://www.haomeiwen.com/subject/hhxdjxtx.html