1. class Solution:
    2. def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
    3. def WB(s):
    4. if not s:
    5. return [[]]
    6. if s in memo:
    7. return memo[s]
    8. for i in range(len(s)):
    9. word = s[:i+1]
    10. if word in wordDict:
    11. for subseq in WB(s[i+1:]):
    12. memo[s].append([word] + subseq)
    13. return memo[s]
    14. n = len(s)
    15. memo = defaultdict(list)
    16. result = WB(s)
    17. return [" ".join(i) for i in result]
    1. class Solution:
    2. def wordBreak(self, s, wordDict):
    3. """
    4. :type s: str
    5. :type wordDict: Set[str]
    6. :rtype: List[str]
    7. """
    8. return self.helper(s, wordDict, {})
    9. def helper(self, s, wordDict, memo):
    10. if s in memo: return memo[s]
    11. if not s: return []
    12. res = []
    13. for word in wordDict:
    14. #if not s.startswith(word):
    15. # continue
    16. if word != s[:len(word)]:
    17. continue
    18. if len(word) == len(s):
    19. res.append(word)
    20. else:
    21. resultOfTheRest = self.helper(s[len(word):], wordDict, memo)
    22. for item in resultOfTheRest:
    23. item = word + ' ' + item
    24. res.append(item)
    25. memo[s] = res
    26. return res