LeetCode 119. Pascal's Triangle II
2017-04-13 13:28
465 查看
题目:
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?
思路:
大方向是先计算中间值之间的值,然后再更新中间值之后的值,记得要区别rowIndex的奇偶,具体思路见注释。
代码:
**输出结果:**3ms
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?
思路:
大方向是先计算中间值之间的值,然后再更新中间值之后的值,记得要区别rowIndex的奇偶,具体思路见注释。
代码:
class Solution { public: vector<int> getRow(int rowIndex) { vector<int> res(rowIndex+1, 1);//初始化rowIndex+1大小的vector,值为1 int end = rowIndex / 2 + 1;//取中间索引 int pre = 1;//从第二个数开始 int newend=end;//保留初始end值 while (pre<end-1){//如果还没到中间值 for (int i = pre; i>0; --i){//i从pre开始到第1个为止,当前值更新为原有值和前一个的值的和 res[i] = res[i] + res[i - 1]; } ++pre; } if (rowIndex % 2 != 0){//如果rowIndex为奇数,++newend ++newend; } for (int j = 0; j < newend - 1;++j){//外循环要newend-1次 for (int k = end-1; k >0; --k){//内循环为从end-1的索引开始,到第1个位置 res[k] += res[k - 1];//当前值更新为原有值和前一个的值的和 } } pre = 0, end = rowIndex;//只是为了利用无用变量,因为之前只是将中间值及之前的值更新了,现在更新后面的 while (pre <= end){//如果pre小于end(pre初始为0,end初始为最后一个值的索引) res[end] = res[pre];//给全面的值赋值,因为是对称 ++pre; --end; } return res; } };
**输出结果:**3ms
相关文章推荐
- [leetcode]: 119. Pascal's Triangle II
- LeetCode 119. Pascal's Triangle II
- LeetCode 119: Pascal's Triangle II
- LeetCode 119. Pascal's Triangle II
- [Leetcode] 119. Pascal's Triangle II 解题报告
- Leetcode 119 Pascal's Triangle II
- 【leetcode】119. Pascal's Triangle II
- 【LeetCode】 119. Pascal's Triangle II
- LeetCode 119. Pascal's Triangle II
- LeetCode WIith JS || 119. Pascal's Triangle II
- Leetcode#119. Pascal's Triangle II(杨辉三角II)
- [LeetCode]119 Pascal's Triangle II
- LeetCode 119. Pascal's Triangle II
- [LeetCode] 119. Pascal's Triangle II
- leetcode119~Pascal's Triangle II
- LeetCode-119:Pascal's Triangle II (返回杨辉三角指定行)
- [LeetCode By Python]119. Pascal's Triangle II
- LeetCode119. Pascal's Triangle II
- [C语言] leetcode 119. Pascal's Triangle II
- 【Leetcode】119. Pascal's Triangle II