Word Break II

Given a non-empty string_s_and a dictionary_wordDict_containing a list of non-empty words, add spaces in_s_to construct a sentence where each word is a valid dictionary word. Return all such possible sentences.

Note:

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

  • You may assume the dictionary does not contain duplicate words.

Example

Example 1:

Input: 

s = "catsanddog"
wordDict = ["cat", "cats", "and", "sand", "dog"]

Output:
[
  "cats and dog",
  "cat sand dog"
]

Example 2:

Input:

s = "pineapplepenapple"
wordDict = ["apple", "pen", "applepen", "pine", "pineapple"]

Output:

[
  "pine apple pen apple",
  "pineapple pen apple",
  "pine applepen apple"
]

Explanation:
 Note that you are allowed to reuse a dictionary word.

Example 3:

Note

与之前Word Break I不同的是,这里要求打印出所有组合,所以memo变成这个substring对应其可以被拆出来的list of String,dfs的返回值也是list of String。所以还是遍历所有分割点,分割点之前prefix需要在字典里,分割点之后的suffix送入递归,把其返回结果依次加入

Time worst:O(2^n) -> O(n^2)

Space: O(2^n)

解释:

这种例子中,意味着 string 中任意分割方案,都是合法的分割方案,也就是说,“aaaaaa..” 存在多少中分割方法,就是多少个答案。那么有多少个分割方法呢?2^(n-1)。因为任何两个a之间的间隙都可以选择割开或者不割开。那么n-1个间隙,就有 2^(n-1) 个分割方案。

Code

Last updated