140. Word Break II

Photo by Clark Tibbs on Unsplash

140. Word Break II

class Solution:
    def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
        # Have to use entire s
        # Can have 0 or more breaks
        # All should be valid words
        ans = []
        def isValidWord(word):
            return word in wordDict
        def backtrack(index, tempWord, tempSent):
            if index >= len(s):
                if isValidWord(tempWord):
                    findSent = tempSent + " " + tempWord
                    findSent = findSent.strip()
                    ans.append(findSent)
                    print('-' * 20)
                return

            if isValidWord(tempWord):
                backtrack(index + 1, s[index], tempSent + " " + tempWord)

            backtrack(index + 1, tempWord + s[index] , tempSent)

        backtrack(0, "", "")
        return ans