Word Break II(dp with memo)
Example
import collections
class Solution:
"""
@param: s: A string
@param: wordDict: A set of words.
@return: All possible sentences.
"""
def wordBreak(self, s, wordDict):
# write your code here
cache = collections.defaultdict(list)
return self.dfs(s, wordDict,cache)
def dfs(self, s, wordDict, cache):
if s in cache:
return cache[s]
res = []
if s == '':
return ['']
for i in range(len(s)):
if s[:i+1] in wordDict:
ns = s[i+1:] #i+1这里,loop处理每个i
c= "" if ns=="" else " "
res += [s[:i+1] +c+ x for x in self.dfs(ns, wordDict,cache)]
cache[s] = res
return resLast updated