[leetcode-119]Pascal's Triangle II (c++)
2015-08-12 10:28
477 查看
问题描述:
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?
分析:这个可以直接利用数学方法来构造。比如n(j) = n(j-1)*(n-i)/(i+1)。注意如果直接相乘的话,很可能会导致溢出,因此需要强制转换成long型或者更高数据类型。
代码如下:0ms
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?
分析:这个可以直接利用数学方法来构造。比如n(j) = n(j-1)*(n-i)/(i+1)。注意如果直接相乘的话,很可能会导致溢出,因此需要强制转换成long型或者更高数据类型。
代码如下:0ms
[code]class Solution { public: vector<int> getRow(int rowIndex) { vector<int> res; res.push_back(1); int prev = 1; for(int i = 0;i<rowIndex-1;i++){ int val = (long)prev*(rowIndex-i)/(i+1); res.push_back(val); prev = val; } if(rowIndex>0) res.push_back(1); return res; } };
相关文章推荐
- c++ 抽象类
- C++ const 强转下指针的诡异输出
- 黑马程序员——C语言笔记之指针
- android编译surface c++程序时,报错缺少.o文件
- C++之:函数调用的名字查找与继承
- C++之:对象的静态类型和动态类型
- C C++中ThreadLocal的实现方式
- C++中关于数组与指针的几处难点
- [leetcode-118]Pascal's Triangle(c++)
- 字节存储排序:大端和小端的判别及转换
- C语言中extern的用法
- C++中 || 运算
- C++投票系统说明文档
- ACM挑战程序设计竞赛1.1抽签
- [C语言][LeetCode][27]Remove Element
- C++ <VS2008> 使用Excel类创建,读取,查询,写入,修改,删除
- c++ 11 游记 之 decltype constexpr
- [C语言][LeetCode][189]Rotate Array
- OC语言-02-OC语言-基础知识
- C语言中的const