刷题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方法才能往下生成我们想要的结果。

原创粉丝点击