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;
}