美文网首页
118. Pascal's Triangle

118. Pascal's Triangle

作者: YellowLayne | 来源:发表于2017-06-19 22:44 被阅读0次

1.描述

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]
]

2.分析

3.代码

/**
 * 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) {
    if (numRows <= 0) return NULL;
    *columnSizes = (int*)malloc(sizeof(int) * numRows);
    int** array = (int**)malloc(sizeof(int*) * numRows);
    for (unsigned int i = 0; i < numRows; ++i) {
        (*columnSizes)[i] = i + 1;
        int* row = (int*)malloc(sizeof(int) * (i+1));
        row[0] = 1;
        for (unsigned int j = 1; j< i + 1; ++j) {
            row[j] = array[i-1][j-1] + array[i-1][j];
        }
        row[i] = 1;
        array[i] = row;
    }
    return array;
}

相关文章

网友评论

      本文标题:118. Pascal's Triangle

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