
目标
给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 k 行。
示例:
输入: 3
输出: [1,3,3,1]
进阶: 你可以优化你的算法到 O(k) 空间复杂度吗?
实现:
C :
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
int* getRow(int rowIndex, int* returnSize) {
int ** c = NULL;
c=(int**)malloc(sizeof(int*)*(rowIndex+1));
*returnSize = (int)malloc(sizeof(int)*(rowIndex+1));
for (int i = 0 ; i < rowIndex+1;i++) {
c[i] = (int*)malloc((i+1) * sizeof(int));
for (int j = 0; j < i+1; j++) {
if( i == 0 || j==i) {
c[i][j] = 1;
} else {
c[i][j] = c[i-1][j-1]+c[i-1][j];
}
}
}
(*returnSize) = rowIndex+1;
return c[rowIndex];
}
输入:
4
输出:
[1,4,6,4,1]




近期评论