首页 > 代码库 > [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");
}
}
[Leetcode]-Pascal's Triangle
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。