Python实现"杨辉三角"的三种方法

给定一个非负整数numRows,生成杨辉三角的前numRows行

在杨辉三角中,每个数是它左上方和右上方的数的和 

Example:

Input: 5
Output:
[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

1:根据numRows的大小简单迭代

def generate(self, numRows):
        """
        :type numRows: int
        :rtype: List[List[int]]
        """
        if numRows==0:
            return []
        if numRows==1:
            return[[1]]
        if numRows==2:
            return [[1],[1,1]]
        numRows -= 2
        rList = [[1],[1,1]]
        while numRows>0:
            newList = [1]
            for i in range(len(rList[-1])-1):
                newList.append(rList[-1][i]+rList[-1][i+1])
            newList.append(1)
            rList.append(newList)
            numRows -= 1
        return rList

2:利用zip()和sum()这两个方法(参考他人代码)

zip()可参考:http://www.runoob.com/python/python-func-zip.html

sum()可参考:http://www.runoob.com/python/python-func-sum.html

def generate(self, numRows):
        """
        :type numRows: int
        :rtype: List[List[int]]
        """
        l1 = [1]
        l2 = []
        n = 0
        while n<numRows:
            l2.append(l1)
            l1 = [sum(t) for t in zip([0]+l1, l1+[0])]
            n += 1
        return l2

3:利用map()方法(参考他人代码)

map()可参考:http://www.runoob.com/python/python-func-map.html

def generate(self, numRows):
        """
        :type numRows: int
        :rtype: List[List[int]]
        """
        if numRows==0:
            return []
        l1 = [[1]]
        n = 1
        while n<numRows:
            l1.append(map(lambda x,y:x+y, [0]+l1[-1], l1[-1]+[0]))
            n += 1
        return l1

算法题来自:https://leetcode-cn.com/problems/pascals-triangle/description/

猜你喜欢

转载自blog.csdn.net/qiubingcsdn/article/details/82459533