题目描述
Given an index k, return the k th 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?
题目大意
给定一个索引值k,返回杨辉三角中第k行索引的结果
例如,给定:k=3,
返回:[1,3,3,1]
空间复杂度要求为O(k)。
思路
也是一个杨辉三角的问题,但是这个题不要求返回整个杨辉三角,只要求返回索引行的结果,而且要求空间复杂度为O(k)。
因此想到用动规的思想,用一维数组的动态更新来模拟二维数组,但是,考虑每一行的时候,当从前向后递归时是有后效影响的,因此采用从后向前迭代的方式。
代码
#include<iostream>
#include<vector>
using namespace std;
vector<int> getRow(int rowIndex)
{
rowIndex++; // 行索引加一是真正的行数
vector<int > res(rowIndex, 1);
// 第一二行均为1,从第三行才需要进行计算操作
// 因此索引从2开始
for(int i=2; i<rowIndex; i++)
{
for(int j=i-1; j>0; j--)
{
// 每次从后向前迭代
res[j] = res[j-1] + res[j];
}
}
return res;
}
int main()
{
vector<int > res;
int n;
while(true)
{
cout<<"输入:";
cin>>n;
res = getRow(n);
cout<<"输出:";
for(int i=0; i<res.size(); i++)
{
cout<<res[i]<<' ';
}
cout<<endl;
}
return 0;
}
运行结果

以上。
网友评论