Merge pull request #2508 from MatthewMaxy/master

添加0279.完全平方数 Python2版本 ; 0139.单词拆分Python DP剪枝方法 ; 背包问题理论基础多重背包 Python解法;添加0583.两个字符串的删除操作 Python解法2
This commit is contained in:
程序员Carl
2024-05-03 20:42:08 +08:00
committed by GitHub
4 changed files with 83 additions and 0 deletions

View File

@ -394,7 +394,28 @@ class Solution:
dp[j] = dp[j] or (dp[j - len(word)] and word == s[j - len(word):j])
return dp[len(s)]
```
DP剪枝
```python
class Solution(object):
def wordBreak(self, s, wordDict):
# 先对单词按长度排序
wordDict.sort(key=lambda x: len(x))
n = len(s)
dp = [False] * (n + 1)
dp[0] = True
# 遍历背包
for i in range(1, n + 1):
# 遍历单词
for word in wordDict:
# 简单的 “剪枝”
if len(word) > i:
break
dp[i] = dp[i] or (dp[i - len(word)] and s[i - len(word): i] == word)
return dp[-1]
```
### Go

View File

@ -271,7 +271,27 @@ class Solution:
# 返回结果
return dp[n]
```
```python
class Solution(object):
def numSquares(self, n):
# 先把可以选的数准备好,更好理解
nums, num = [], 1
while num ** 2 <= n:
nums.append(num ** 2)
num += 1
# dp数组初始化
dp = [float('inf')] * (n + 1)
dp[0] = 0
# 遍历准备好的完全平方数
for i in range(len(nums)):
# 遍历背包容量
for j in range(nums[i], n+1):
dp[j] = min(dp[j], dp[j-nums[i]]+1)
# 返回结果
return dp[-1]
```
### Go

View File

@ -234,6 +234,25 @@ class Solution:
return dp[-1][-1]
```
> 版本 2
```python
class Solution(object):
def minDistance(self, word1, word2):
m, n = len(word1), len(word2)
# dp 求解两字符串最长公共子序列
dp = [[0] * (n+1) for _ in range(m+1)]
for i in range(1, m+1):
for j in range(1, n+1):
if word1[i-1] == word2[j-1]:
dp[i][j] = dp[i-1][j-1] + 1
else:
dp[i][j] = max(dp[i-1][j], dp[i][j-1])
# 删去最长公共子序列以外元素
return m + n - 2 * dp[-1][-1]
```
### Go
```go

View File

@ -204,6 +204,29 @@ class multi_pack{
```
### Python
```python
C, N = input().split(" ")
C, N = int(C), int(N)
# value数组需要判断一下非空不然过不了
weights = [int(x) for x in input().split(" ")]
values = [int(x) for x in input().split(" ") if x]
nums = [int(x) for x in input().split(" ")]
dp = [0] * (C + 1)
# 遍历背包容量
for i in range(N):
for j in range(C, weights[i] - 1, -1):
for k in range(1, nums[i] + 1):
# 遍历 k如果已经大于背包容量直接跳出循环
if k * weights[i] > j:
break
dp[j] = max(dp[j], dp[j - weights[i] * k] + values[i] * k)
print(dp[-1])
```
### Go