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?
我写的代码,用的递归,Time Limit Exceeded。
class Solution {
public:
int value(int row,int pos)
{
int val;
if(row==1)
return 1;
if(pos==row)
return 1;
if(pos==0)
return 1;
val=value(row-1,pos-1)+value(row-1,pos);
}
vector<int> getRow(int rowIndex) {
vector<int> tri;
int i;
if(rowIndex==0)
{
tri.push_back(1);
return tri;
}
else if(rowIndex==1)
{
tri.push_back(1);
tri.push_back(1);
return tri;
}
else
{
for(i=0;i<=rowIndex/2;i++)
{
if(i==0||i==rowIndex)
tri.push_back(1);
else
tri.push_back(value(rowIndex,i));
}
for(;i<=rowIndex;i++)
{
tri.push_back(tri[rowIndex-i]);
}
}
return tri;
}
};
参考别人的代码,原文地址
点击打开链接
class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> tri(rowIndex+1);
int i,j;
for(i=0;i<=rowIndex;i++)
{
for(j=i;j>=0;j--)
{
if(j==i||j==0)
{
tri[j]=1;
}
else
{
tri[j]=tri[j]+tri[j-1];
}
}
}
return tri;
}
};