Merge pull request #2154 from jianghongcheng/master

merge
This commit is contained in:
程序员Carl
2023-06-27 19:33:05 +08:00
committed by GitHub
5 changed files with 92 additions and 1 deletions

View File

@ -397,7 +397,39 @@ class Solution:
```
动态规划(版本五)
```python
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid):
if obstacleGrid[0][0] == 1:
return 0
m, n = len(obstacleGrid), len(obstacleGrid[0])
dp = [0] * n # 创建一个一维列表用于存储路径数
# 初始化第一行的路径数
for j in range(n):
if obstacleGrid[0][j] == 1:
break
dp[j] = 1
# 计算其他行的路径数
for i in range(1, m):
if obstacleGrid[i][0] == 1:
dp[0] = 0
for j in range(1, n):
if obstacleGrid[i][j] == 1:
dp[j] = 0
continue
dp[j] += dp[j - 1]
return dp[-1] # 返回最后一个元素,即终点的路径数
```
### Go
```go

View File

@ -262,10 +262,11 @@ class Solution:
# 计算切割点j和剩余部分(i-j)的乘积,并与之前的结果进行比较取较大值
dp[i] = max(dp[i], max((i - j) * j, dp[i - j] * j))
dp[i] = max(dp[i], (i - j) * j, dp[i - j] * j)
return dp[n] # 返回最终的计算结果
```
动态规划版本二
```python

View File

@ -383,6 +383,21 @@ class Solution:
return True
return False
```
卡哥版(简化版)
```python
class Solution:
def canPartition(self, nums: List[int]) -> bool:
if sum(nums) % 2 != 0:
return False
target = sum(nums) // 2
dp = [0] * (target + 1)
for num in nums:
for j in range(target, num-1, -1):
dp[j] = max(dp[j], dp[j-num] + num)
return dp[-1] == target
```
二维DP版
```python

View File

@ -282,7 +282,35 @@ class Solution:
return dp1 # 返回到达楼顶的最小花费
```
动态规划(版本三)
```python
class Solution:
def minCostClimbingStairs(self, cost: List[int]) -> int:
dp = [0] * len(cost)
dp[0] = cost[0] # 第一步有花费
dp[1] = cost[1]
for i in range(2, len(cost)):
dp[i] = min(dp[i - 1], dp[i - 2]) + cost[i]
# 注意最后一步可以理解为不用花费,所以取倒数第一步,第二步的最少值
return min(dp[-1], dp[-2])
```
动态规划(版本四)
```python
class Solution:
def minCostClimbingStairs(self, cost: List[int]) -> int:
n = len(cost)
prev_1 = cost[0] # 前一步的最小花费
prev_2 = cost[1] # 前两步的最小花费
for i in range(2, n):
current = min(prev_1, prev_2) + cost[i] # 当前位置的最小花费
prev_1, prev_2 = prev_2, current # 更新前一步和前两步的最小花费
return min(prev_1, prev_2) # 最后一步可以理解为不用花费,取倒数第一步和第二步的最少值
```
### Go
```Go
func minCostClimbingStairs(cost []int) int {

View File

@ -238,6 +238,21 @@ class Solution:
return total_sum - dp[target] - dp[target]
```
卡哥版(简化版)
```python
class Solution:
def lastStoneWeightII(self, stones):
total_sum = sum(stones)
target = total_sum // 2
dp = [0] * (target + 1)
for stone in stones:
for j in range(target, stone - 1, -1):
dp[j] = max(dp[j], dp[j - stone] + stone)
return total_sum - 2* dp[-1]
```
二维DP版
```python