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. You may assume the dictionary does not contain duplicate words.
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”].
问题描述
给定非空字符串s和非空字符串列表wordDict,向s中加入空格使得空格分隔的每个单词出现在wordDict中。wordDict不包含重复单词。返回s加入空格后所有可能的字符串。
问题分析
dfs + memorization
算法思想以s = “catsanddog”,dict = [“cat”, “cats”, “and”, “sand”, “dog”]为例
s.substring(0, 3) = “cat”出现在dict中,那么递归s.substring(3),将”cat”添加到返回结果中
得到的结果是”cat sand dog”
s.substring(0, 4) = “cats”出现在dict中,那么递归s.substring(4),将”cats”添加到返回结果中
得到的结果是”cats and dog”
综合一下
得到[“cat sand dog”, “cats and dog”]
解法(dfs + memorization)
class Solution {
public List<String> wordBreak(String s, List<String> wordDict) {
//字典集合
Set<String> dict = new HashSet();
for(String str : wordDict) dict.add(str);
return backTrack(s, dict, new HashMap());
}
public List<String> backTrack(String s, Set<String>dict, Map<String, List<String>> memo){
//memo保存字符串s对应的所有分隔可能性
if(memo.containsKey(s)) return memo.get(s);
List<String> res = new ArrayList();
for(int i = 0;i < s.length();i++){
String temp = s.substring(0, i + 1);
//若字典集合包含temp,递归字串s.substring(i + 1),将temp添加到返回结果中
//注意,若到达末尾,直接加入temp即可
if(dict.contains(temp)){
if(i == s.length() - 1){
res.add(temp);
}else{
List<String> subres = backTrack(s.substring(i + 1), dict, memo);
if(subres.size() != 0){
for(String str : subres){
res.add(temp + " " + str);
}
}
}
}
}
memo.put(s, res);
return res;
}
}