当我们需要改变数组的值时,如果从前往后遍历,有时会带来很多麻烦,比如需要插入值,导致数组平移,或者新的值覆盖了旧有的值,但旧有的值依然需要被使用。这种情况下,有时仅仅改变一下数组的遍历方向,就会避免这些困难。
最直观的一题是 剑指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.从后往前遍历,简洁。