LeetCode 119. Pascal's Triangle II
2016-07-24 11:58
309 查看
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> lastRow;
vector<int> res;
int i;
for(i = 0; i <= rowIndex; i ++){
res.clear();
res.push_back(1);
lastRow.push_back(1);
int j;
for(j = 1; j < i; j ++){
res.push_back(lastRow[j - 1] + lastRow[j]);
}
if(i) res.push_back(1);
lastRow = res;
}
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> lastRow; vector<int> res; if(rowIndex == 0){ res.push_back(1); return res; } int i; for(i = 0; i <= rowIndex; i ++){ res.clear(); int j; for(j = 0; j <= i; j ++){ res.push_back(1); } for(j = 1; j <= i / 2; j ++){ res[j] = res[i - j] = lastRow[j - 1] + lastRow[j]; } lastRow.clear(); lastRow = res; } return res; } };
写法二:
class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> lastRow;
vector<int> res;
int i;
for(i = 0; i <= rowIndex; i ++){
res.clear();
res.push_back(1);
lastRow.push_back(1);
int j;
for(j = 1; j < i; j ++){
res.push_back(lastRow[j - 1] + lastRow[j]);
}
if(i) res.push_back(1);
lastRow = res;
}
return res;
}
};
相关文章推荐
- gcd中同步异步并行串行线程数目的关系
- 2016暑期计划
- 继承中成员方法的关系:
- 应用泰勒公式求极限时的无穷小分析
- [算法学习笔记]基于最大堆实现最大优先队列
- 方法重写:
- Oracle sqlplus登录的三种方式
- [转] 常用SQL查询语句
- HTML5 LocalStorage 本地存储(转)
- hdu 1811 Rank of Tetris(并查集+拓扑)
- 树的同构 poj 1635
- nyoj 915 +-字符串
- JPA的查询语言—使用原生SQL
- WaitForSingleObject函数的使用
- syscore
- 平板比较
- 架构实例之Demo_JSP
- **JQUERY**系列一:jQuery简介
- LFU cache Java
- 原生JS实现AJAX、JSONP及DOM加载完成事件