Search⌘ K
AI Features

Word Break II

Explore how to apply dynamic programming to segment a string into valid words from a given dictionary. Learn to generate all possible sentences by efficiently combining words through memoization and recursion. This lesson helps you implement Word Break II solutions in Go by understanding problem constraints and leveraging design patterns.

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.

Examples

canvasAnimation-image
1 / 2

Understand the problem

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

Word Break II

1.

What is the output if the following input string and dictionary are provided as input?

s = “pineapplepenapple”

word_dict = [“apple”, “pen”, “applepen”, “pine”, “pineapple”]

A.

[“pine apple pen apple”, “pineapple pen apple”, “pine applepen apple”]

B.

[“pine apple pen apple”, “pine applepen apple”]

C.

[“pineapple pen apple”]

D.

[]


1 / 3

Figure it out!

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Sequence - Vertical
Drag and drop the cards to rearrange them in the correct sequence.

1
2
3
4
5
6

Try it yourself

Implement your solution in the following coding playground.

Go
usercode > main.go
package main
func wordBreak(s string, wordDict []string) []string {
// Replace this placeholder return statement with your code
return make([]string, 0)
}
Word Break II