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?

118. Pascal's Triangle 的拓展,给一个索引k,返回杨辉三角的第k行。

解法:题目要求优化到 O(k) 的空间复杂,那么就不能把每行都记录下来,而只是记录前一行和当前行。

Java:

public class Solution {
public List<Integer> getRow(int rowIndex) {
List<Integer> res = new ArrayList<>();
int curr[] = new int[rowIndex + 1];
int prev[] = new int[rowIndex + 1];
prev[0] = 1; for(int row = 1; row <= rowIndex; row++) {
curr[0] = 1;
curr[row] = 1;
for(int i = 1; i < row; i++)
curr[i] = prev[i] + prev[i - 1];
int[] swap = curr;
curr = prev;
prev = swap;
} for(int i = 0; i <= rowIndex; i++)
res.add(prev[i]);
return res;
}
}  

Java:

public class Solution {
public List<Integer> getRow(int rowIndex) {
ArrayList<Integer> row = new ArrayList<Integer>();
for (int i=0; i<rowIndex+1; i++){
row.add(0,1);
for(int j=1; j<row.size()-1;j++){
row.set(j, row.get(j)+row.get(j+1));
}
}
return row;
}
}  

Python:

class Solution:
# @return a list of integers
def getRow(self, rowIndex):
result = [0] * (rowIndex + 1)
for i in xrange(rowIndex + 1):
old = result[0] = 1
for j in xrange(1, i + 1):
old, result[j] = result[j], old + result[j]
return result

C++:  

class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> out;
if (rowIndex < 0) return out; out.assign(rowIndex + 1, 0);
for (int i = 0; i <= rowIndex; ++i) {
if ( i == 0) {
out[0] = 1;
continue;
}
for (int j = rowIndex; j >= 1; --j) {
out[j] = out[j] + out[j-1];
}
}
return out;
}
};

C++:

class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> result(rowIndex+1, 0);
result[0] = 1;
for(int i=1; i<rowIndex+1; i++)
for(int j=i; j>=1; j--)
result[j] += result[j-1];
return result;
}
};  

类似题目:

[LeetCode] 118. Pascal's Triangle 杨辉三角

All LeetCode Questions List 题目汇总

最新文章

  1. GUI基础学习
  2. C#设计模式系列:状态模式(State)
  3. Swift3.0语言教程使用字符串创建和初始化字符串
  4. 编写高效的js/jQuery代码 :rocket:
  5. Hibernate映射一对多双向关联关系及部门关联属性
  6. QT-- MainWindow外的cpp文件调用ui
  7. HDU 1907 (博弈) John
  8. android图片切换ImageSwichter的动画切换效果
  9. 【HDOJ】1908 Double Queue
  10. ExtJS学习-----------Ext.String,ExtJS对javascript中的String的扩展
  11. c++策略模式
  12. Chrome浏览器加载CSS文件TTFB waiting超时的奇葩问题
  13. 通过枚举enum实现单例
  14. Hibernate 系列教程15-一级缓存
  15. 【二】python内置类型
  16. gdb分析core文件
  17. 第一次写博客,就写如何向外行介绍自己做的是什么,那个我是做web的
  18. Spring Cloud(十二):分布式链路跟踪 Sleuth 与 Zipkin【Finchley 版】
  19. Git入门—创建项目
  20. 第十二周翻译-《Pro SQL Server Internals, 2nd edition》

热门文章

  1. QA流程
  2. Codeforces D. Intercity Travelling(区间组合)
  3. P2602 [ZJOI2010]数字计数(递推)
  4. windows 上运行 sslocal 提示 libcrypto(OpenSSL) not found 解决办法
  5. ML.NET学习笔记 ---- 系列文章
  6. NOIP2019 PJ 对称二叉树
  7. iptables 通用语句
  8. Django API接口FK ManyTo Many 模板
  9. gdb命令行
  10. js之大文件分段上传、断点续传