刷题1
来源:互联网 发布:linux 设置系统时区 编辑:程序博客网 时间:2024/06/07 10:09
python 刷Leetcode: Pascal’s Triangle II
题目描述
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?
即返回第k行的杨辉三角
杨辉三角(Pascal’s Triangle)描述
1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1
为更好的发现规律,改写:
1 0
1 1 0
1 2 1 0
1 3 3 1 0
1 4 6 4 1 0
1 5 10 10 5 1 0
0是为了构造而添加的辅助的,这样下一行的值就是对应上一行的值加它前面的值.
例如:第k行第i行L[k][i]=L[k-1][i]+L[k-1][i-1]
首先需要实现杨辉三角的函数,为节省内存,可以利用yield 生成器。
def pascal(self): L = [1] while True: yield L L.append(0) L=[L[i]+L[i-1] for i in xrange(len(L))]
正式代码:
class Solution(object): def getRow(self, rowIndex): """ :type rowIndex: int :rtype: List[int] """ ans =[] f1 = self.pascal() for x in xrange(rowIndex+1): ans = f1.next() return ans def pascal(self): L = [1] while True: yield L L.append(0) L = [L[i - 1] + L[i] for i in xrange(len(L))]
备注:
刚开始我用了:
for x in xrange(rowIndex+1): ans = self.pascal().next()return ans
这就错了,因为这里for循环每次调用self.pascal().next()都是从初始开始,即得到的结果总是L=[1],解决的方法是先定义一个引用f1,然后每次循环调用的都是f1引用,这样才能next方法才能往下生成我们想要的结果。
阅读全文
0 0
- 刷题1
- LeetCode 刷题1
- 剑指Offer 刷题(1)
- LeetCode刷题(1)
- Leetcode刷题(1)
- 刷题9-10(1)
- LeetCode刷题(1)
- [刷题]Count 1 in Binary
- Leecode 刷题1 Two Sum
- lintcode刷题(python)(1)
- leetcode刷题two sum 1
- 刷题
- 刷题
- 刷题
- 刷题
- 刷题
- 刷题。。。
- 刷题
- hdu 5726 GCD 【RMQ+st】
- 【字符串】字符串替换空格
- JQuery中eq()和get()的区别
- 2017年7月18日Spring随笔
- 盒子模型
- 刷题1
- Cocos2d-x《雷电大战》(2)-精灵随手指移动,你点哪我走哪!
- 利用MIME类型根据apk路径自动安装apk之application/vnd.android.package-archive
- 百练_2693:最远距离
- C3P0配合DBUtils开源框架实现对数据库的增删改查及批处理功能实战
- getopt_long_only解析带多个参数值和对optind的个人理解
- ZOJ 3471Most Powerful(状态压缩DP)
- UNP第二章 TCP、UDP和SCTP
- Object Hook 简单介绍