您的位置:首页 > 其它

leetcode 118 Pascal's Triangle(难易度:Easy)

2015-10-05 12:14 387 查看

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]
]

代码:

/**
* 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 (numRows <= 0) {
*columnSizes = NULL;
*returnSize = 0;
return NULL;
}
// *columnSizes = new int[numRows];
*columnSizes = (int *)malloc(numRows * sizeof(int));
// int **PascalTriangle = new int *[numRows];
int **PascalTriangle = (int **)malloc(numRows * sizeof(int *));
int i;
for (i = 0; i < numRows; i++) {
(*columnSizes)[i] = i + 1;
PascalTriangle[i] = (int *)malloc((i + 1) * sizeof(int));
PascalTriangle[i][0] = 1;
PascalTriangle[i][i] = 1;
for (int j = 1; j < i; j++) {
PascalTriangle[i][j] = PascalTriangle[i - 1][j - 1] + PascalTriangle[i - 1][j];
}
}
*returnSize = numRows;
return PascalTriangle;
}
原题地址:https://leetcode.com/problems/pascals-triangle/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode