【leetcode】帕斯卡三角形

问题描述:

给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。

《【leetcode】帕斯卡三角形》

在杨辉三角中,每个数是它左上方和右上方的数的和。

示例:

输入: 5
输出:
[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

提交代码思路:

观察每行与前一行的关系,可以发现后一行比前一行多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) {
    if(numRows<=0 || columnSizes==NULL)
    {
        return NULL;
    }
    int** result=(int**)malloc(sizeof(int*)*numRows);//返回二维数组的行数为n,每行的列数存在×columnSizes数组中
    *columnSizes=(int *)malloc(sizeof(int)*numRows);
    memset(*columnSizes,0,sizeof(int)*numRows);
    
    int i=0;
    for(i=0;i<numRows;i++)
    {
        result[i]=(int*)malloc(sizeof(int)*(i+1));//每行数组的空间分配
        memset(result[i],0,sizeof(int)*(i+1));
        (*columnSizes)[i]=i+1;//每行数组的元素个数
        printf("*columnSizes[%d]=%d\n",i,(*columnSizes)[i]);
        result[i][0]=1,result[i][i]=1;//每行首尾元素都为1
        int j=1;
        while(j<=i/2)
        {
            result[i][j]=result[i-1][j-1]+result[i-1][j];
            result[i][i-j]=result[i][j];
            j++;
        }
    }
    return result;
}

    原文作者:杨辉三角问题
    原文地址: https://blog.csdn.net/yansj_scu/article/details/81006681
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞