Pascal's Triangle II
2016-05-20 14:38
357 查看
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;
if(rowIndex<0)
return res;
res.push_back(1);
for(int i=2;i<= rowIndex+1;i++)
{
int pre=1;
for(int j=1;j<i-1;j++)
{
int tmp=res[j];
res[j]+=pre;
pre=tmp;
}
res.push_back(1);
}
return res;
}
};
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;
if(rowIndex<0)
return res;
res.push_back(1);
for(int i=2;i<= rowIndex+1;i++)
{
int pre=1;
for(int j=1;j<i-1;j++)
{
int tmp=res[j];
res[j]+=pre;
pre=tmp;
}
res.push_back(1);
}
return res;
}
};
相关文章推荐
- maven笔记
- 文章标题
- iOS学习之—— CGAffineTransform
- __block __weak
- KMP算法 - 字符串匹配的
- iOS 9 导入类库全面详尽过程(Ruby安装->CocoaPods安装->导入类库)
- 【地铁】北京地铁退卡点
- undefined reference to libiconv_open'
- 解决eclipse中无法直接调用的一些方法的办法如下 ---- 类 Method
- Apache activemq example
- MyBatis 学习总结(二)——MyBatis 实现 crud 操作
- Ubuntu下adb 显示insufficient permissions for device,或Eclipse中DDMS设备显示?????
- 计算机无法启动mysql服务 1067 错误 ,进程意外终止
- 虚拟机vm_state状态
- RecyclerView进阶(1)
- bzoj3309: DZY Loves Math
- 机器人
- [转]THINKPHP--MVC模式
- LESS框架笔记
- Java 静态语句块、语句块、构造函数