首页 > 代码库 > [Leetcode]-Pascal's Triangle

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

题目:依据numRows生成帕斯卡三角形。帕斯卡三角形原理点击这里
思路:帕斯卡三角形的每行首、位元素都为1。其它的元素为上一行两个元素之和:

if(0 == j || i == j)   r[i][j] = 1;
else                   r[i][j] = r[i-1][j-1] + r[i-1][j];

注意事项:
1、numRows为0的时候返回0
2、一定要自己分配内存空间

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

/**
 * Return an array of arrays of size *returnSize.
 * 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* returnSize) {

    if(0 == numRows) return 0;
    *returnSize = numRows  ; 
    int i = 0, j = 0;
    int** r = (int**)malloc(sizeof(int*) * numRows);
    //int*cn    = (int*)malloc(sizeof(int) * numRows);
    *columnSizes = (int*)malloc(sizeof(int) * numRows);
    //*columnSizes = cn;
    for(i=0;i<numRows;i++)
    {
        //cn[i] = i + 1;
        columnSizes[0][i] = i + 1 ;
        r[i]  = (int*)malloc(sizeof(int)*(i+1));
    }

    for(i=0;i<numRows;i++)
    {
        for(j=0;j<i+1;j++)
        {
            if(0 == j || i == j) r[i][j] = 1;
            else r[i][j] = r[i-1][j-1] + r[i-1][j];
        }
    }
    return r;
}

int main()
{   
    int num = 3 ;
    int *columnSizes ;//每一行有几个元素
    int returnSize = 0;
    int **r = generate(num,&columnSizes,&returnSize);
    int i = 0;
    int j = 0;
    printf("toal element size is : %d\n",returnSize);
    for(i=0;i<num;i++)
    {
        printf("%d row have %d element \n",i,columnSizes[i]);
    }

    for(i=0;i<num;i++)
    {
        for(j=0;j<i+1;j++)
            printf("r[%d][%d]  = %d\n",i,j,r[i][j]);

        printf("\n");
    }
}
<script type="text/javascript"> $(function () { $(‘pre.prettyprint code‘).each(function () { var lines = $(this).text().split(‘\n‘).length; var $numbering = $(‘
    ‘).addClass(‘pre-numbering‘).hide(); $(this).addClass(‘has-numbering‘).parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($(‘
  • ‘).text(i)); }; $numbering.fadeIn(1700); }); }); </script>

[Leetcode]-Pascal&#39;s Triangle