Q:
Given a string s and a dictionary of strings wordDict, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in any order.
Note that the same word in the dictionary may be reused multiple times in the segmentation.
Example 1:
Input: s = "catsanddog", wordDict = ["cat","cats","and","sand","dog"]
Output: ["cats and dog","cat sand dog"]
A: To solve this problem, we need record every result of match, dynamic programming can not complete it. Therefore, I use DFS to search all possible answers and record every result.
class Solution {
public List<String> wordBreak(String s, List<String> wordDict) {
ans = new ArrayList<>();
res = new ArrayList<>();
dfs(s,wordDict,0);
return ans;
}
void dfs(String s, List<String> wordDict, int start) {
if(start>=s.length()){
ans.add(new String(String.join(" ",res)));
}else{
for(String w:wordDict){
int end = start + w.length();
if(end<=s.length() && w.equals(s.substring(start,end))){
res.add(w);
dfs(s,wordDict,end);
res.remove(res.size()-1);
}
}
}
}
List<String> ans;
List<String> res;
}