Pascal's Triangle II
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?
思路:使用O(K)空间的话,就需要从后往前加
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?
思路:使用O(K)空间的话,就需要从后往前加
vector 初始化 vector<int> vint(rowIndex,1);
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> getRow(int rowIndex) {
rowIndex++;
vector<int> vint(rowIndex,1);
if(rowIndex<=2)
return vint;
for(int i=2;i<rowIndex;++i)
for(int j=i-1;j>=1;--j){
vint[j]+=vint[j-1];
}
return vint;
}
};
int main(){
Solution s;
vector<int> vint = s.getRow(0);
for(int i=0;i<vint.size();++i)
cout<<vint[i]<<" ";
cout<<endl;
vint = s.getRow(1);
for(int i=0;i<vint.size();++i)
cout<<vint[i]<<" ";
cout<<endl;
vint = s.getRow(2);
for(int i=0;i<vint.size();++i)
cout<<vint[i]<<" ";
cout<<endl;
vint = s.getRow(3);
for(int i=0;i<vint.size();++i)
cout<<vint[i]<<" ";
cout<<endl;
vint = s.getRow(4);
for(int i=0;i<vint.size();++i)
cout<<vint[i]<<" ";
cout<<endl;
return 0;
}