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?
相比之前, 有所改动
class Solution { public: vector<int> getRow(int rowIndex) { vector<int>ve1; ve1.push_back(1); if(rowIndex==0) return ve1; ve1.clear(); ve1.push_back(1); ve1.push_back(1); if(rowIndex==1) return ve1; int i; int j; vector<int>ve2; for(i=2;i<=rowIndex;i++) { ve2.swap(ve1); ve1.clear(); ve1.push_back(1); for(j=0;j<i-1;j++) ve1.push_back(ve2[j]+ve2[j+1]); ve1.push_back(1); } return ve1; } };
用的space为两个vector<int>
ve1和ve2的长度为 k, k+1
O(space) = 2k+1