【代码随想录训练营】【Day 49】【动态规划-8】| Leetcode 139
需强化知识点
- 多重背包:将其展开为01背包
题目
139. 单词拆分
- 注意 要保证 单词构成的有序性,先遍历背包,再遍历物品
- 回溯法
python
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
# 0-i 的 单词能否由 字典构成
dp = [False] * (len(s) + 1)
dp[0] = True
# 先遍历背包,再遍历物品
for i in range(1, len(s) + 1):
for word in wordDict:
if i >= len(word) and word == s[i-len(word):i]:
dp[i] = dp[i] or dp[i-len(word)]
return dp[len(s)]
- 感受 backtracking 返回布尔值
python
class Solution:
def backtracking(self, s: str, wordSet: set[str], startIndex: int) -> bool:
# 边界情况:已经遍历到字符串末尾,返回True
if startIndex >= len(s):
return True
# 遍历所有可能的拆分位置
for i in range(startIndex, len(s)):
word = s[startIndex:i + 1] # 截取子串
if word in wordSet and self.backtracking(s, wordSet, i + 1):
# 如果截取的子串在字典中,并且后续部分也可以被拆分成单词,返回True
return True
# 无法进行有效拆分,返回False
return False
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
wordSet = set(wordDict) # 转换为哈希集合,提高查找效率
return self.backtracking(s, wordSet, 0)