118. 杨辉三角

问题描述

https://leetcode.cn/problems/pascals-triangle/description/

解题思路

杨辉三角可以用动态规划来解决,但它的解题思路跟一般的DP不一样,一般的DP只有一个数组,它牵扯到多个数组。

它的状态转移方程是:res[cur][j] = res[cur-1][j-1]+res[cur-1][j]

而它的边界条件是,它只计算两边,不计算中间。

代码

class Solution:
    def generate(self, numRows: int) -> List[List[int]]:
        if numRows == 1:
            return [[1]]
        if numRows == 2:
            return [[1], [1,1]]
        res = [[1], [1,1]]
        for i in range(3, numRows+1):
            cur_res = [1 for j in range(i)]
            for j in range(1, len(cur_res)-1):
                cur_res[j] = res[-1][j-1]+res[-1][j]
            res.append(cur_res)
        return res

 代码二

class Solution:
    def generate(self, numRows: int):
        res = [[1]]
        if numRows == 1:
            return res
        for i in range(2, numRows + 1):
            tmp_row = [1] * i
            for j in range(1, i-1):
                tmp_row[j] = res[-1][j-1] + res[-1][j]
            res.append(tmp_row)
        return res

 

posted @ 2023-01-15 17:34  BJFU-VTH  阅读(21)  评论(0编辑  收藏  举报