问题描述:
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]
源码:
杨辉三角主要有下列五条性质:
- 杨辉三角以正整数构成,数字左右对称,每行由1开始逐渐变大,然后变小,回到1。
- 第行的数字个数为个。
- 第行的第个数字为组合数 。
- 第行数字和为 。
- 除每行最左侧与最右侧的数字以外,每个数字等于它的左上方与右上方两个数字之和(也就是说,第行第个数字等于第 行的第 个数字与第个数字的和)。这是因为有组合恒等式:
但是只能用O(K)的空间,所以我们每次从后向前遍历,这样保证前面的值不被覆盖。
时间100%,空间100%。
class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> res(rowIndex + 1);
res[0] = 1;
for (int i = 1; i <= rowIndex; ++i) {
for (int j = i; j >= 1; --j) {
res[j] += res[j - 1];
}
}
return res;
}
};
还有一种直接从C的定义出发,比如C(7, 2)=A(7, 2) / A(2, 2), C(7, 3)=A(7, 3) / A(3, 3),因此 C(7, 3)=C(7, 2) * (7-2) / 3;
效率同样是双100%,记得用long,否则越界。
class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> result(rowIndex+1, 0);
long div=1, n=rowIndex;
result[0] = 1;
for(int i=1; i<=rowIndex; i++){
result[i] = result[i-1]*(n--)/(div++);
}
return result;
}
};