题目链接

Given a non-negative integer numRows, generate the first numRows of Pascal’s triangle.
Pascal's Triangle

In Pascal’s triangle, each number is the sum of the two numbers directly above it.

Example:

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

解题思路:

  • 这道题就是杨辉三角题。

  • 以前用C语言实现的话,初始化二维数组全部为0,然后每行第一个元素为1,只需要用a[i][j] = a[i-1][j]+a[i-1][j-1]就可以了。

  • 在Python中难点应该就是每行的第一个元素和最后一个元素,最后一个元素通过判断j==i就可以区分了。

python3代码实现:

class Solution(object):
    def generate(self, numRows):
        """
        :type numRows: int
        :rtype: List[List[int]]
        """
        res = []
        for row in range(numRows):
            res.append([1])
            for col in range(1, row + 1):
                if row == col:
                    res[row].append(1)
                else:
                    res[row].append(res[row - 1][col] + res[row - 1][col - 1])
        return res

实现结果:

Pascal's Triangle

相关文章: