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
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.从后往前遍历,简洁。
最直观的一题是 剑指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.从后往前遍历,简洁。
相关文章推荐
- 学会从后往前遍历,例 [LeetCode] Pascal's Triangle II,剑指Offer 题4
- [Leetcode] Pascal's Triangle II
- Leetcode_Pascal's Triangle II
- LEETCODE--Pascal's Triangle II
- Leetcode题解 119. Pascal's Triangle II
- [leetcode, python] Pascal's Triangle II 杨辉三角
- leetcode 119 Pascal's Triangle II
- [leetcode]119. Pascal's Triangle II
- LeetCode(33)-Pascal's Triangle II
- [leetCode]119.Pascal's Triangle II
- LeetCode-Pascal's Triangle II
- Leetcode:119. Pascal's Triangle II(JAVA)
- LeetCode 119. Pascal's Triangle II
- leetcode:Pascal's Triangle II
- Leetcode 119. Pascal's Triangle II
- LeetCode | Pascal's Triangle II
- <LeetCode OJ> 118./119. Pascal's Triangle(I / II)
- LeetCode 119. Pascal's Triangle II
- 【leetcode】Pascal's Triangle II(Java)
- [leetcode] Pascal's Triangle II