Leetcode—— 181.杨辉三角

 181.杨辉三角

给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。

在杨辉三角中,每个数是它左上方和右上方的数的和。

示例:

输入: 5
输出:
[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/pascals-triangle
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路:

1.确定状态

  • dp[i][j] 指第 i 行第 j 列的数字。

2.转移方程

  • dp[i][j] = dp[i][j-1] + dp[i][j]

3.边界情况

  • 初始化全为0,将边界设为1

程序代码:

class Solution:
    def generate(self, numRows):
        dp = [[0] * n for n in range(1,numRows+1)]
        for i in range(numRows):
            dp[i][0] = dp[i][-1] = 1
        for i in range(0,numRows):
            for j in range(i+1):
                if dp[i][j] == 0:
                    dp[i][j] = dp[i-1][j-1] + dp[i-1][j]
        return dp

s = Solution()
print(s.generate(5))
发布了246 篇原创文章 · 获赞 155 · 访问量 14万+

猜你喜欢

转载自blog.csdn.net/suxiaorui/article/details/103939482