[Leetcode]-Pascal's Triangle
Posted yangykaifa
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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");
}
}
以上是关于[Leetcode]-Pascal's Triangle的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode118:Pascal's Triangle
[Leetcode]-Pascal's Triangle
leetcode笔记:Pascal's Triangle
leetcode:Pascal's Triangle