Description
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 1:
1 | Input: |
Example 2:
1 | Input: |
Example 3:
1 | Input: |
解法
最开始采用暴力DFS的方法,果断超时了,这个时候考虑剪枝,用dp数组计算位置i是否为可分位置,添加判断即可通过。
具体代码如下:
1 | class Solution { |