题目:
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.
解释:
杨辉三角系列的第二题。可以直接像I一样保存每一行的结果,然后返回最后一行即可。
python代码:
class Solution:
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
result=[]
for numRow in range(rowIndex+1):
tmp=[0]*(numRow+1)
tmp[0]=1
tmp[-1]=1
for i in range (1,len(tmp)-1):
tmp[i]=result[numRow-1][i-1]+result[numRow-1][i]
result.append(tmp)
return result[-1];
c++代码:
class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<vector<int>> result;
for (int i=0;i<rowIndex+1;i++)
{
vector<int> tmp(i+1,0);
tmp[0]=1;
tmp[i]=1;
for (int j=1;j<i;j++)
{
tmp[j]=result[i-1][j-1]+result[i-1][j];
}
result.push_back(tmp);
}
return result[rowIndex];
}
};
还要求用O(k)的空间复杂度完成,也就是说不能每一次都保存所有的结果。要注意到杨辉三角对称的性质。
python代码(注意是逆序,然后是向下取整哦):
class Solution:
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
result=[1]
if rowIndex==0:
return result
result.append(1)
if rowIndex==1:
return result
for i in range(2,rowIndex+1):
result.append(1)
n=len(result)
#逆序的原因是防止前面变了影响后面
for j in range(n-2,0,-1):
if (j>=n//2):
result[j]=result[j]+result[j-1]
else:
result[j]=result[n-1-j]
return result;
c++代码:
class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int>result={1};
if (rowIndex==0)
return result;
result.push_back(1);
if(rowIndex==1)
return result;
for(int i=2;i<=rowIndex;i++)
{
result.push_back(1);
int n =result.size();
for (int j=n-2;j>0;j--)
{
if(j>=n/2)
result[j]+=result[j-1];
else
result[j]=result[n-1-j];
}
}
return result;
}
};
总结:
记住O(k)时间复杂度的写法。