- class Solution:
- def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
- dp=[[0 for _ in range(len(obstacleGrid[0])+1)] for _ in range(len(obstacleGrid)+1)]
- flag=[[True for _ in range(len(obstacleGrid[0])+1)] for _ in range(len(obstacleGrid)+1)]
- for i in range(len(obstacleGrid)):
- for j in range(len(obstacleGrid[0])):
- if obstacleGrid[i][j]==1:
- dp[i][j]=0
- flag[i][j]=False
- for i in range(len(obstacleGrid[0])):
- if flag[0][i]==False:
- break
- dp[0][i]=1
- for i in range(len(obstacleGrid)):
- if flag[i][0]==False:
- break
- dp[i][0]=1
- for i in range(1,len(obstacleGrid)):
- for j in range(1,len(obstacleGrid[0])):
- if flag[i][j]==False:
- dp[i][j]=0
- elif flag[i-1][j] and flag[i][j-1]:
- dp[i][j]=dp[i-1][j]+dp[i][j-1]
- elif flag[i-1][j]==False and flag[i][j-1]:
- dp[i][j]=dp[i][j-1]
- elif flag[i-1][j] and flag[i][j-1]==False:
- dp[i][j]=dp[i-1][j]
- else:
- dp[i][j]=0
- return dp[len(obstacleGrid)-1][len(obstacleGrid[0])-1]
卡了半天,突然想起来
马兰过河卒 - Gzz's space (guanzhongzheng.online)
于是就过了
- class Solution:
- def integerBreak(self, n: int) -> int:
- dp=[0]*(n+1)
- dp[2]=1
- for i in range(3,n+1):
- for j in range(0,i//2+1):
- dp[i]=max(j*(i-j),j*dp[i-j],dp[i])
- return dp[n]
1.dp[0],dp[1]无意义。题目要求乘积最大,初始化为0,不影响题解
2.for j in range(0,i//2+1):基本不等式,拆两个的情况相等乘积最大,拆多个更不肯接近i//2+1,i//2则错误
3.j*(i-j)拆一个,j*dp[i-j]拆多个,因为有for循环所以也要和之前的dp[i]比较