mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 04:06:51 +08:00
添加0139.单词拆分 Python DP剪枝方法
This commit is contained in:
@ -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:
|
||||
|
Reference in New Issue
Block a user