from collections import deque
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
if len(s) == 0:
return []
word_set = {word for word in wordDict}
dp = [0 for _ in range(len(s)+1)]
dp[0] = 1
for i in range(1, len(s)+1):
for j in range(i):
if dp[j]and s[j:i] in word_set:
dp[i] = 1
break
res = []
def dfs(s, length, word_set, res, path, dp):
if length == 0:
res.append(" ".join(path))
return
for i in range(length):
if dp[i]:
suffix = s[i:length]
if suffix in word_set:
path.appendleft(suffix)
dfs(s, i, word_set, res, path, dp)
path.popleft()
if dp[-1]:
queue = deque()
dfs(s, len(s), word_set, res, queue, dp)
return res
Runtime: 44 ms, faster than 85.87% of Python3 online submissions for Word Break II.
Memory Usage: 12.9 MB, less than 100.00% of Python3 online submissions for Word Break II.
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
from collections import defaultdict
if len(s) == 0:
return []
cuts = [False]*(len(s)+1)
cuts[0] = True
segs = defaultdict(list)
for i in range(1, len(s)+1):
for j in range(i):
rst = cuts[j]and (s[j:i]in wordDict)
if rst is True:
cuts[i] = rst
segs[j].append(i)
ret = []
def backtrack(segs, start, path, ret):
if start == len(s):
ret.append(" ".join(path))
return True
else:
for j in segs[start]:
path.append(s[start:j])
backtrack(segs, j, path, ret)
path.pop()
if cuts[-1]is True:
backtrack(segs, 0, [], ret)
return ret
Runtime: 112 ms, faster than 19.34% of Python3 online submissions for Word Break II.
Memory Usage: 12.8 MB, less than 100.00% of Python3 online submissions for Word Break II.