码迷,mamicode.com
首页 > 编程语言 > 详细

Leetcode with Python -> Array

时间:2017-12-25 23:22:24      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:oop   tco   list   elf   dex   desc   space   self   ext   

118. Pascal‘s Triangle

Given numRows, generate the first numRows of Pascal‘s triangle.

For example, given numRows = 5,
Return

[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]
class Solution(object):
    def generate(self, numRows):
        """
        :type numRows: int
        :rtype: List[List[int]]
        """
        res = [[1]]
        for i in range(1,numRows):
            res += [map(lambda x, y:x+y,res[-1]+[0],[0]+res[-1])]
        return res[:numRows]
    
    # [[1]]+[0] -> [[1],0]
    # [[1]]+[0,1] ->[[1],0,1]
    # [[1]]+[[0]] -> [[1],[0]]
    # [[1]]+0 -> error
    # the code is elegant, but slow. the reason lies in the fact that it generates too much list while looping
    # be careful when numRows is 0, res[:numRows] will return [] when it happens

119. 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?

class Solution(object):
    def getRow(self, rowIndex):
        """
        :type rowIndex: int
        :rtype: List[int]
        """

        
        res = [1]
        for i in range(0, rowIndex):
            res = [ i+j for i,j in zip(res + [0], [0] + res)]
        return res
    
    # list can‘t be added elementwisely with +

 

Leetcode with Python -> Array

标签:oop   tco   list   elf   dex   desc   space   self   ext   

原文地址:https://www.cnblogs.com/DianeSoHungry/p/8111533.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!