当前位置:网站首页>【动态规划】杨辉三角
【动态规划】杨辉三角
2022-04-23 06:11:00 【小风_】
给定一个非负整数 *
numRows
,*生成「杨辉三角」的前numRows
行。在「杨辉三角」中,每个数是它左上方和右上方的数的和。
链接:https://leetcode-cn.com/problems/pascals-triangle/
定义: d p [ i ] [ j ] dp[i][j] dp[i][j]表示索引位置 i , j i,j i,j的值
边界条件: d p [ 0 ] [ 0 ] = 1 , d p [ 1 ] [ 0 ] = d p [ 1 ] [ 1 ] = 1 dp[0][0]=1,dp[1][0]=dp[1][1]=1 dp[0][0]=1,dp[1][0]=dp[1][1]=1
状态转移方程: d p [ i ] [ j ] = d p [ i − 1 ] [ j − 1 ] + d p [ i − 1 ] [ j ] , i dp[i][j] = dp[i-1][j-1]+dp[i-1][j]~,~i dp[i][j]=dp[i−1][j−1]+dp[i−1][j] , i不为边界,边界为1
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
# dp[i][j] = dp[i-1][j]+dp[i-1][j-1]
dp = []
curRow = 0
while curRow < numRows: # 行
if curRow==0:
dp.append([1])
elif curRow==1:
dp.append([1,1])
else:
temp = []
for i in range(curRow + 1): # 列
if i==0 or i == curRow: # 如果遇到了边界
temp.append(1)
else:
temp.append(dp[curRow-1][i]+dp[curRow-1][i-1])
dp.append(temp)
curRow += 1
return dp
如果只需要序列索引为numRows
(索引从0开始)的值,那么在上面代码基础上,简单改动一下即可,相关链接
class Solution:
def getRow(self, numRows: int) -> List[int]:
dp = []
curRow = 0
while curRow < numRows+1: # 行
if curRow==0:
dp=[1]
elif curRow==1:
dp=[1,1]
else:
temp = []
for i in range(curRow + 1): # 列
if i==0 or i == curRow: # 如果遇到了边界
temp.append(1)
else:
temp.append(dp[i]+dp[i-1])
dp=temp
curRow += 1
return dp
版权声明
本文为[小风_]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_33952811/article/details/119328154
边栏推荐
猜你喜欢
随机推荐
如何对多维矩阵进行标准化(基于numpy)
组件化学习(1)思想及实现方式
扫雷小游戏
Encapsulate a set of project network request framework from 0
Component learning (2) arouter principle learning
webView因证书问题显示一片空白
adb shell 常用命令
adb shell top 命令详解
Cause: dx. jar is missing
MySQL5. 7 insert Chinese data and report an error: ` incorrect string value: '\ xb8 \ XDF \ AE \ xf9 \ X80 at row 1`
利用队列实现栈
face_recognition人脸检测
BottomSheetDialogFragment 与 ListView RecyclerView ScrollView 滑动冲突问题
MySQL笔记3_约束_主键约束
Binder mechanism principle
iTOP4412 SurfaceFlinger(4.0.3_r1)
C# EF mysql更新datetime字段报错Modifying a column with the ‘Identity‘ pattern is not supported
adb shell常用模拟按键keycode
Recyclerview batch update view: notifyitemrangeinserted, notifyitemrangeremoved, notifyitemrangechanged
Kotlin征途之data class [数据类]