题目描述
Given a string s and a dictionary of words dict, add spaces in sto 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"].
解题思路:
- 利用dp数组记录s中任意一段子串是否包含dict的一个单词
- DFS(深度优先) 从后往前匹配
import java.util.*;
public class Solution {
ArrayList<String> reverseRes = new ArrayList<>();
ArrayList<String> res = new ArrayList<>();
int[][] dp;
public ArrayList<String> wordBreak(String s, Set<String> dict) {
int len = s.length();
dp = new int[len][len];
for (int i = 0; i < len; i++) {
for (int j = i; j < len; j++) {
String tmp = s.substring(i, j + 1);
if (dict.contains(tmp)) {
dp[i][j] = 1;
}
}
}
dfs(s.length() - 1, "", s);
for (int i = reverseRes.size() - 1; i >= 0; i--) {
res.add(reverseRes.get(i));
}
return res;
}
public void dfs(int length, String post, String s) {
if (length == -1) {
reverseRes.add(post);
}
for (int i = 0; i <= length; i++) {
if (dp[i][length] == 1) {
String nPost = post.equals("")? s.substring(i, length + 1) : s.substring(i, length + 1) + " " + post;
dfs(i - 1, nPost, s);
}
}
}
}