Pascal's Triangle II--LeetCode
來源:程序員人生 發(fā)布時間:2015-04-20 08:17:57 閱讀次數(shù):3173次
題目:
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?
思路:只用1個向量作為終究結(jié)果的存儲空間便可,中間1直使用這個向量來更新。
//第k層的數(shù)
void PascaltriangleKth(int k)
{
vector<int> result(k,0);
int tmp1,tmp;
for(int i=0;i<k;i++)
{
for(int j=0;j<=i;j++)
{
if(j==0 || j==i)
{
tmp = 0;
tmp1 = 1;
result[j]=1;
}
else
{
tmp = result[j];
result[j] += tmp1;
tmp1 = tmp;
}
}
}
for(int j=0;j<result.size();j++)
cout<<result[j]<<" ";
cout<<endl;
}
生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈