题目
Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle.
Note that the row index starts from 0.
In Pascal's triangle, each number is the sum of the two numbers directly above it.
Example:
Input: 3
Output: [1,3,3,1]
Follow up:
Could you optimize your algorithm to use only O(k) extra space?
解析
典型的杨辉三角求某一行的所有值。此处要注意的是rowIndex从0开始,题目中要求优化空间复杂度为O(k),这意图就很明显了,即让我们找到规律后依次赋值。
因此题目即展开为求第n行的所有组合数。
右侧的部分也可以写成,
n(n-1)(n-2)…(n-r+1) / r!
写成这种形式以便在求组成数进行循环的时候比较方便。
代码
// 求组合数,使用long以防止int越界
long getCombination(int n, int m) {
long res = 1;
for (int i = 1; i <= m; ++i) {
res = (res * (n - m + i)) / i;
}
return res;
}
int* getRow(int rowIndex, int* returnSize) {
(* returnSize) = rowIndex + 1;
int* returnArr = (int*)malloc((*returnSize) * sizeof(int));
returnArr[0] = returnArr[(*returnSize) - 1] = 1;
if (rowIndex == 0) {
returnArr[0] = 1;
return returnArr;
}
for (int i = 1; i < ((*returnSize) / 2 + 1); ++i) {
returnArr[i] = returnArr[(*returnSize) - i - 1] =
(int)getCombination(rowIndex, i); // 强转为int
}
return returnArr;
}
网友评论