原题:
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?
和上一道题一样不过只要输出最后一行,而且要求只用O(k) 的额外空间,这里我有个小技巧:从后往前加可以在一个容器内运算并且不会覆盖被加数,结果如下:
Success
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Pascal's Triangle II.
Memory Usage: 8.3 MB, less than 95.51% of C++ online submissions for Pascal's Triangle II.
代码:
class Solution {
public:
vector getRow(int rowIndex) {
vector r;
r.push_back(1);
if(rowIndex==0){return r;}
for(int i=1;i<=rowIndex;i++){
r.push_back(1);
for(int j=i-1;j>0;j--){
r[j]+=r[j-1];
}
}
return r;
}
};