[leetcode] 119. Pascal's Triangle II

题目

Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle.

In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:

img

Example 1:

Input: rowIndex = 3
Output: [1,3,3,1]

Example 2:

Input: rowIndex = 0
Output: [1]

Example 3:

Input: rowIndex = 1
Output: [1,1]

Constraints:

  • 0 <= rowIndex <= 33

Follow up: Could you optimize your algorithm to use only O(rowIndex) extra space?

思路

递推式计算帕斯卡三角中每一行列表。

代码

python版本:

class Solution:
    def getRow(self, rowIndex: int) -> List[int]:
        res = [1]

        def calc(nums: List[int]):
            last = 0
            for i in range(0, len(nums)):
                nums[i], last = nums[i]+last, nums[i]
            nums.append(1)
        [calc(res) for _ in range(rowIndex)]
        return res

posted @ 2022-06-10 16:25  frankming  阅读(25)  评论(0编辑  收藏  举报