题解
思路
代码
class Solution:
### 0201 动态规划(84 ms,14.9 MB)
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
n = len(s)
# dp[i]表示s的前i个字符能否由wordDict中单词表示
dp = [False] * (n + 1)
dp[0] = True
# 以每个字符作为开头进行遍历
for i in range(n):
# 判断后续字符能否被表示
for j in range(i+1, n+1):
# 若之前i个字符能被表示 且 当前字符也能够被表示
if dp[i] and s[i:j] in wordDict:
dp[j] = True
return dp[-1]
140. 单词拆分 II
- 题解
- 2024.4最新通过的code(注意:此版code未使用备忘录,即可通过!!!)
class Solution:
# 超时
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
res = []
wordDict = set(wordDict)
def dfs(wordDict, temp, pos):
# pos来到字符串的最后一位时,表示遍历完毕,即可返回
if pos == len(s):
res.append(" ".join(temp))
return
for i in range(pos, len(s)+1):
if s[pos:i] in wordDict:
temp.append(s[pos:i])
dfs(wordDict, temp, i)
temp.pop()
dfs(wordDict, [], 0) # pos位置从0开始
return res
- 官方题解分析