041-力扣刷题-118--杨辉三角

给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。 PascalTriangleAnimated2.gif 示例:

1
2
3
4
5
6
7
8
9
输入: 5
输出:
[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution(object):
    def generate(self, numRows):
        """
        :type numRows: int
        :rtype: List[List[int]]
        """
        result = []
        for i in range(numRows):
            result.append([])  #循环对每一行进行操作,每一行都是一个一维的list
            for j in range(i+1): #对这一行的每一个元素进行操作,因为没行正好是i+1个元素
                if j in (0,i):  #如果遍历这一行的元素进行操作的时候,首尾索引的元素存的应该都是1
                    result[i].append(1) #取出二维列表的这一行进行添加操作
                else:#否则的是上一行的前一列跟上一行的同一列的值进行相加
                    result[i].append(result[i-1][j-1]+result[i-1][j])
        return result

就按照原理做就好了