题目:
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”],
* the solution is [“cats and dog”, “cat sand dog”].
本题没有想出使用dfs的做法,所以找了一下解法。
思路:核心是字符串中的单词和字典项比较
1.本题使用了dp和dfs两种算法
2.根据题意,背包中不在放flag,而是存放和题意相符的单词
3.利用dfs递归算法取得所有结果
代码:
public static List<String> wordBreak(String s, Set<String> dict) {
List<String>[] dp = new List[s.length() + 1];
dp[0] = new ArrayList();
for (int i = 0 ; i < s.length() ; i++) {
if (dp[i] == null) {
continue;
}
for (String word : dict) {
int len = word.length();
int end = i + len;
if(end > s.length())
continue;
if (s.substring(i , end).equals(word)) {
if (dp[end] == null) {
dp[end] = new ArrayList();
}
dp[end].add(word);
}
}
}
List<String> result = new ArrayList<String>();
if (dp[s.length()] == null) {
return result;
}
List<String> temp = new ArrayList<String>();
dfs(dp, s.length(), result, temp);
return result;
}
/**
* 递归解法,需要有一个终止条件
* 此问题的终止条件是end <= 0
* @param dp
* @param end
* @param result
* @param tmp
*/
public static void dfs(List<String> dp[],int end,List<String> result, List<String> tmp){
if (end <= 0) {
String path = tmp.get(tmp.size() - 1);
for (int i=tmp.size()-2; i>=0; i--) {
path += " " + tmp.get(i);
}
result.add(path);
return;
}
for (String word : dp[end]) {
tmp.add(word);
dfs(dp, end - word.length(), result, tmp);
tmp.remove(tmp.size() - 1);
}
}
@Test
public static void main(String[] args){
String str = "catsanddog";
String[] strs = {"cat", "cats", "and", "sand", "dog"};
Set<String> dict = new HashSet<String>(Arrays.asList(strs));
System.out.println(wordBreak(str, dict));
}