118. Pascal's Triangle

题目描述

求指定阶数的杨辉三角,如输入:5,则返回:

[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

我的解法——两层循环

  • 两层循环直接搞,但有点小trick(见代码)
  • n2的复杂度。
  • 结果:beat 54.22%
class Solution(object):
    def generate(self, numRows):
        """
        :type numRows: int
        :rtype: List[List[int]]
        """
        res = []
        for i in range(numRows): 
            now = [1] * (i + 1)  # 小技巧,开始直接设置为全1
            for j in range(1,i):
                now[j] = res[i - 1][j - 1] + res[i - 1][j]
            res.append(now)
        return res

参考答案

https://leetcode.com/problems/pascals-triangle/solution/