您的位置:首页 > 其它

leetcode:Pascal's Triangle II 学会从后往前遍历

2017-02-07 12:25 281 查看
当我们需要改变数组的值时,如果从前往后遍历,有时会带来很多麻烦,比如需要插入值,导致数组平移,或者新的值覆盖了旧有的值,但旧有的值依然需要被使用。这种情况下,有时仅仅改变一下数组的遍历方向,就会避免这些困难。

 

最直观的一题是 剑指Offer上的面试题 4

另外一道例题,就是LeetCode上的 Pascal's Triangle II

Pascal's Triangle II

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?

class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> res(rowIndex+1,0);
res[0]=1;
for (int i = 0; i <= rowIndex; ++i)
{
for (int j = i; j > 0; --j)
{
res[j]=res[j]+res[j-1];
}
}

return res;
}
};

注意:1.从后往前遍历,简洁。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: