"""
Given a dictionary of words and a string made up of those words (no spaces), 
return the original sentence in a list. If there is more than one possible reconstruction, 
return any of them. If there is no possible reconstruction, then return null.

For example, given the set of words 'quick', 'brown', 'the', 'fox', 
and the string "thequickbrownfox", you should return ['the', 'quick', 'brown', 'fox'].

Given the set of words 'bed', 'bath', 'bedbath', 'and', 'beyond', 
and the string "bedbathandbeyond", 
return either ['bed', 'bath', 'and', 'beyond] or ['bedbath', 'and', 'beyond'].
"""

def dfs(s, wordDict, memo):
    if s in memo:
        return memo[s]
    if not s:
        return []
        
    res = []
    for word in wordDict:
        if not s.startswith(word):
            continue
        # if word == s:
        if len(word) == len(s):
            res.append(word)
        else:
            temp_results = dfs(s[len(word):], wordDict, memo)
            for temp in temp_results:
                temp = word + " " + temp
                res.append(temp)
        
    memo[s] = res
    return res
    
def wordBreak(s, wordDict):
    if len(s) == 0 or len(wordDict) == 0:
        return []
        
    return dfs(s, wordDict, {})
    
