本题题目要求如下:
Given an index k, return the kth row of the Pascal's triangle.
For example, given k = 3,
Return [1,3,3,1]
.
Note:
Could you optimize your algorithm to use only O(k) extra space?
举个栗子:
比如我们要求k = 4的结果:
设一个vector,[1,0,0,0,0]
而由上面可知k=3时是[1,3,3,1,0]
此时我从中点开始计算即A[2] = A[2]+A[1] = 6. A[1] = A[1] + A[0] = 4,再拷贝到右半边即可,有代码量更短的代码,但是我感觉这种思路更适合我。
代码如下:
class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> res(rowIndex+1, 0);
res[0] = 1;
for (int i = 0; i <= rowIndex; ++i) {
for (int j = i / 2; j > 0; --j)
res[j] = res[j] + res[j-1];
for (int j = 0; j <= i / 2; ++j)
res[i-j] = res[j];
}
return res;
}
};