Given numRows, generate the first numRows of Pascal's triangle.
For example, given numRows = 4,
Return
Return
[ [1], [1,1], [1,2,1], [1,3,3,1] ]
C program :
int** generate(int numRows, int** columnSizes) {
int i, j;
int numColumns = 0;
*columnSizes = malloc(numRows*sizeof(int));
int** result = (int**)malloc(numRows*sizeof(int*));
for (i = 0; i < numRows; i++)
result[i] = (int*)malloc((i+1)*sizeof(int));
for (i = 0; i < numRows; i++) {
result[i][0] = result[i][i] = 1;
for (j = 0; j < i; j++) {
result[i][j] = result[i-1][j-1] + result[i-1][j];
}
numColumns++;
*(*columnSizes+i) = numColumns;
}
return result;
}
C++ program :
class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<vector<int>>result(numRows);
for (int i = 0; i < numRows; i++) {
result[i].resize(i+1);
result[i][0] = result[i][i] = 1;
for (int j = 0; j < i ; j++) {
result[i][j] = result[i-1][j-1] + result[i-1][j];
}
}
return result;
}
};
No comments:
Post a Comment