pascal三角原理+zip用法-【leetcode119-pascal triangle2】
来源:互联网 发布:用vb制作倒计时 编辑:程序博客网 时间:2024/06/01 10:14
一、题目
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(object): def getRow(self, rowIndex): """ :type rowIndex: int :rtype: List[int] """ array = [] for i in range(rowIndex+1): array.append([1]*(i+1)) for j in range(i): array[i][j] = array[i-1][j-1] + array[i-1][j] array[i][0] = array[i][-1] = 1 return array[rowIndex]三、用pascal原理,注意zip的使用
class Solution(object): def getRow(self, rowIndex): """ :type rowIndex: int :rtype: List[int] """ row = [1] for i in range(rowIndex): row = [x + y for x, y in zip([0]+row,row+[0])] return row四、pascal三角原理
Say we have the current layer [1, 2, 1]. We then make 2 copies of this layer, add 0 to the start of one copy, and add 0 to the end of one copy; then we have [0, 1, 2, 1] and [1, 2, 1, 0]. Then we can perform the element-wise add operation and we would have [1, 3, 3, 1]. This is from the definition of Pascal's Triangle.
五、zip用法
a = [1,2,3] b = [4,5,6] c = [4,5,6,7,8]zipped = zip(a,b)>>>[(1, 4), (2, 5), (3, 6)]zip(a,c)>>>[(1, 4), (2, 5), (3, 6)]zip(*zipped)>>>[(1, 2, 3), (4, 5, 6)]
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]zip(*a)>>>[(1, 4, 7), (2, 5, 8), (3, 6, 9)]map(list,zip(*a))>>>[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
阅读全文
0 0
- pascal三角原理+zip用法-【leetcode119-pascal triangle2】
- leetcode119.Pascal'sTriangleII
- LeetCode119:Pascal's Triangle II
- leetcode119~Pascal's Triangle II
- LeetCode119. Pascal's Triangle II
- LeetCode119 Pascal's Triangle II
- LeetCode119. Pascal's Triangle II
- Pascal三角
- Pascal三角
- LeetCode119——Pascal's Triangle II
- LeetCode119—Pascal's Triangle II
- 打印出Pascal三角:
- Pascal's Triangle 打印Pascal三角 @LeetCode
- pascal
- Pascal
- PASCAL
- Pascal基本用法
- 【LeetCode】Pascal's Triangle (杨辉三角)
- 案例实战:LightningChart集成Dynamotive汽车遥测软件|见证真正无与伦比的性能
- 完美兼容4.4及以上系统实现沉浸式状态栏
- JS中的bool
- hibernate four
- Spring-Mybatis源码分析
- pascal三角原理+zip用法-【leetcode119-pascal triangle2】
- mybatis级联之一对多的关系
- Android O要来了,大家准备好了吗?
- 解决$GLOBALS["HTTP_RAW_POST_DATA"]获取不到数据的问题
- 设计模式-单例模式
- Android MediaScanner 扫描流程
- hibernate笔记11 Hibernate查询方式
- 从 FingBugs的错误来看JAVA代码质量(一)
- 实验三 端口扫描实验