添加0139.单词拆分 Python DP剪枝方法

This commit is contained in:
matthew
2024-04-02 23:58:58 +08:00
parent 1d16381a7d
commit 6dd9d117ff

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