杨辉三角

本文主要讲解关于杨辉三角的两道题目

第一题

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

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

具体题目见链接:数组和字符串 - LeetBook - 力扣(LeetCode)全球极客挚爱的技术成长平台 (leetcode-cn.com)

思路
根据杨辉三角的定义直接编写程序

/**
 * Return an array of arrays of size *returnSize.
 * The sizes of the arrays are returned as *returnColumnSizes array.
 * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
 */
int** generate(int numRows, int* returnSize, int** returnColumnSizes){
    int i, j;
    *returnSize = numRows;
    int **ans = (int **)malloc(sizeof(int *)*(*returnSize));
    *returnColumnSizes = (int **)malloc(sizeof(int) * numRows);
    for(i = 0; i < numRows; i ++)
    {
       
        (*returnColumnSizes)[i] = i+1;
        ans[i] = (int *)malloc(sizeof(int) * (i+1));
        ans[i][0] = 1;
        ans[i][i] = 1;
        if(i < 2) continue;
        for(j = 1; j < i; j++)
        {
            ans[i][j] = ans[i-1][j-1] + ans[i-1][j];
        }
    }
    return ans;
}

第二题

给定一个非负索引 rowIndex,返回「杨辉三角」的第 rowIndex 行。

在「杨辉三角」中,每个数是它左上方和右上方的数的和。
链接:数组和字符串 - LeetBook - 力扣(LeetCode)全球极客挚爱的技术成长平台 (leetcode-cn.com)

思路
创建一个rowindex+1大小的数组,直接在数组上进行索引为0-rowindex的迭代。

/**
 * Return an array of arrays of size *returnSize.
 * The sizes of the arrays are returned as *returnColumnSizes array.
 * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
 */
int** generate(int numRows, int* returnSize, int** returnColumnSizes){
    int i, j;
    *returnSize = numRows;
    int **ans = (int **)malloc(sizeof(int *)*(*returnSize));
    *returnColumnSizes = (int **)malloc(sizeof(int) * numRows);
    for(i = 0; i < numRows; i ++)
    {
       
        (*returnColumnSizes)[i] = i+1;
        ans[i] = (int *)malloc(sizeof(int) * (i+1));
        ans[i][0] = 1;
        ans[i][i] = 1;
        if(i < 2) continue;
        for(j = 1; j < i; j++)
        {
            ans[i][j] = ans[i-1][j-1] + ans[i-1][j];
        }
    }
    return ans;
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容