oneby7

Recursion and Backtracking Searching with constraints

336. Word Break II

Hard

You are given a string s and a list of words, wordDict. Add spaces to s so that it becomes a sentence made only of words from the list, and return every such sentence.

A sentence keeps the letters of s in their order and puts exactly one space between two words, with no space at the start or the end. A word can be used any number of times, and some words may not be used at all. The list may hold the same word more than once, but each sentence appears in the answer only once. If no sentence can be made, return an empty list.

The sentences can come back in any order, and any order is accepted. The examples list them in sorted order.

Example 1

Input: s = "notebookcase" wordDict = ["note", "book", "notebook", "case", "bookcase", "no"]

Output: ["note book case","note bookcase","notebook case"]

Explanation: These three sentences use every letter. no is a word too, but nothing in the list splits the tebookcase after it, so no sentence starts with no.

Example 2

Input: s = "sandcastles" wordDict = ["sand", "castle", "sandcastle", "cast"]

Output: []

Explanation: Every way of cutting off words leaves s or les at the end, and neither is in the list.

Example 3

Input: s = "lalala", wordDict = ["la", "lala", "la"]

Output: ["la la la","la lala","lala la"]

Explanation: la is listed twice, but each sentence is returned once. la lala and lala la are different sentences, because their spaces are in different places.

Check your understanding

Work out the answer for this input before you write any code.

s = "carpet" wordDict = ["car", "pet", "carp", "et"]

Constraints

  • 1 ≤ s.length ≤ 1000
  • 1 ≤ wordDict.length ≤ 104
  • 1 ≤ wordDict[i].length ≤ 20
  • s and every word hold only lowercase English letters.
  • All the sentences in the answer together hold at most 106 characters, spaces included.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.