...

/

Solution: Word Break II

Solution: Word Break II

Let's solve the Word Break II problem using the Dynamic Programming pattern.

Statement

You are given a string, s, and an array of strings, wordDict, representing a dictionary. Your task is to add spaces to s to break it up into a sequence of valid words from wordDict. We are required to return an array of all possible sequences of words (sentences). The order in which the sentences are listed is not significant.

Note: The same dictionary word may be reused multiple times in the segmentation.

Constraints:

  • 11 \leq s.length 20\leq 20

  • 11 \leq wordDict.length 1000\leq 1000

  • 11 \leq wordDict[i].length 10\leq 10

  • s and wordDict[i] consist of only lowercase English letters.

  • All the strings of wordDict are unique.

Solution

So far, you’ve probably brainstormed some approaches and have an idea of how to solve this problem. Let’s explore some of these approaches and figure out which one to follow based on considerations such as time complexity and any implementation constraints.

Naive approach

The naive approach to solve this problem is to use a traditional recursive strategy in which we take each prefix of the input string, s, and compare it to each word in the dictionary. If it matches, we take the string’s suffix and repeat the process.

Here is how the algorithm works:

  • Base case: If the string is empty, there are no characters in the string that are left to process, so there’ll be no sentences that can be formed. Hence, we return an empty array.

  • Otherwise, the string will not be empty, so we’ll iterate ...