Recursion and Backtracking Searching with constraints
336. Word Break II
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"]
["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"]
[]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"]
["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.
Constraints
1 ≤ s.length ≤ 10001 ≤ wordDict.length ≤ 1041 ≤ wordDict[i].length ≤ 20sand 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.