本文主要讲解关于杨辉三角的两道题目
第一题
给定一个非负整数 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;
}