您的位置:首页 > 其它

(leetcode)Pascal's Triangle II

2015-05-05 10:20 399 查看
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?

这道题是要在O(k)个空间内,找到第k行数据。如果直接顺序计算a[i]=a[i]+[i-1],由于a[i]被替换,所以,在计算a[i+1]时候就出错了。所以使用倒序计算

class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> a;
a.resize(rowIndex+1,0);
a[0]=1;
for(int k =0;k <rowIndex +1;k++)
{
for(int i =k;i>0;i--)
{
a[i]=a[i-1]+a[i];
}
}
return a;
}
};


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: