描述
Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.
Return all such possible sentences.
For example, given
s = “catsanddog”,
dict = [“cat”, “cats”, “and”, “sand”, “dog”].A solution is [“cats and dog”, “cat sand dog”].
分析
在Word Break的基础上,要求返回所有可能的分词结果。我们用一个二维数组A[i][j]
来表示s[j:i]
是不是一个单词(注意下标是反的)。然后通过对A
进行DFS我们可以还原所有的合法组合。理解了之后要写对还是不容易。
代码
Python
1 | class Solution(object): |