难度:Easy
给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 k 行。
在杨辉三角中,每个数是它左上方和右上方的数的和。
示例:
输入: 3
输出: [1,3,3,1]
进阶:
你可以优化你的算法到 O(k) 空间复杂度吗?
优化空间复杂度,需要牺牲一定的时间复杂度,可以使用递归实现。
class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> res;
if (rowIndex==0)
{
res.push_back(1);
return res;
}
if(rowIndex==1)
{
res.push_back(1);
res.push_back(1);
return res;
}
res=getRow(rowIndex-1);
res.push_back(res[rowIndex-1]);
for(int i=rowIndex-1;i>0;i--)
{
res[i]+=res[i-1];
}
return res;
}
};
执行用时 : 8 ms, 在Pascal's Triangle II的C++提交中击败了95.90% 的用户 内存消耗 : 9.2 MB, 在Pascal's Triangle II的C++提交中击败了5.14% 的用户