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?
思路:
假设rowIndex为5
1、当 memspace为3 3 1 0 0,需要计算下一行的时候
2、3->1+3=4,memspace变成 4 3 1 0 0
3、然后3->3+4-1=6,memspace 变成4 6 1 0 0
4、然后哦1-》1+6-4+1=4,memspace 变成4 6 4 0 0
5、最后再末尾加1,memspace变成 4 6 4 1 0 0。
其余行的计算是类似的。。。
/************************************************************************/
/* 需要使用仅仅O(k)的额外空间 */
/************************************************************************/
#include<iostream>
#include<vector>
using namespace std;
vector<int> getRow(int rowIndex) {
int *memspace = (int *)malloc(sizeof(int)*rowIndex);
vector<int> rowValue;
for(int i=0;i<rowIndex;i++)
{
memspace[i] = 0;
}
if(rowIndex == 0)
{
rowValue.push_back(1);
return rowValue;
}
for(int i=0;i<rowIndex-1;i++)
{
memspace[i] = 1;
int index = 0;
while(memspace[index]!=0 && index < rowIndex)
{
int sign = 1;
int value = memspace[index];
for(int k=index-1;k>=0;k--)
{
value = value + sign*memspace[k];
sign = sign*(-1);
}
value = value + sign*1;
memspace[index] = value;
index++;
}
}
memspace[rowIndex-1] = 1;
rowValue.push_back(1);
for(int i=0;i<rowIndex;i++)
{
rowValue.push_back(memspace[i]);
}
return rowValue;
}
int main(void)
{
getRow(1);
system("pause");
return 0;
}