Before solving this, have a look at similar problem “pascal’s triangle”.
Given a non-negative integer numRows, generate the first numRows of Pascal’s triangle.
The only difference between this and the previous question is, we need to use o(k) space.
We follow the same procedure, but instead of using a 2D vector, we use 1D vector to get the result. And we need to return the only K row.
Solution in C++
/*
* File : pascals_triangle_II.cpp
*/
#include<iostream>
#include<string>
#include<vector>
using namespace std;
vector<int> generate(int numRows)
{
vector<int> result(numRows+1, 0);
result[0]=1;
for(int i=1; i<=numRows; i++)
{
for(int j=i; j>=1; j--)
result[j]=result[j]+result[j-1];
}
return result;
}
int main()
{
int numRows = 4;
vector<int>result = generate (numRows);
for (int i = 0; i < result.size(); i++)
{
cout <<result[i] << " ";
}
cout<<endl;
}