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