题目要求:
给你一个字符串 s 和一个字符串列表 wordDict 作为字典。请你判断是否可以利用字典中出现的单词拼接出 s 。
注意:不要求字典中出现的单词全部都使用,并且字典中的单词可以重复使用。
暴力递归
- 从s的下标0开始,依次判断 s.subString(0,i + 1) 在不在wordDict中,若在时,递归判断s剩余的部分s.substring(i + 1) 是否在wordDict中。
- 递归推出的条件是剩余的s == “”
public class WordBreak {
public boolean wordBreak(String s, List<String> wordDict) {
return process(s,wordDict);
}
private boolean process(String s, List<String> wordDict) {
if ("".equals(s)) {
return true;
}
boolean res = false;
for (int i = 0; i < s.length(); i++) {
if (wordDict.contains(s.substring(0, i + 1))) {
// 或操作是必须的,因为for循环会持续更新result的值,如果不用或操作,后面的false会覆盖true
res = res || process(s.substring(i + 1),wordDict);
}
}
return res;
}
}
但是该方法没有ac,超时了。。。
记忆化搜索(也就是加备忘录)
- 现在假设一种情况,假设s = “aaaaaaaaaab”,wordDict = {“a”,“aa”,“aaa”,“aaaa’},在这种情况下,若单独找见“a” 满足条件,则在s中找见两次“a" 以后剩余的s = “aaaaaaaab” 与单独找见一次“aa”以后剩余s = “aaaaaaaab” 相同,这就证明该问题一定存在重复的情况,而加备忘录的原因就是想要我们已经求过的子问题不想再重复求。
public class WordBreak {
public boolean wordBreak2(String s, List<String> wordDict) {
Map<String,Boolean> map = new HashMap<>();
return process2(s,wordDict,map);
}
private boolean process2(String s, List<String> wordDict,Map<String,Boolean> map) {
if ("".equals(s)) {
return true;
}
if (map.get(s) != null) {
return map.get(s);
}
boolean res = false;
for (int i = 0; i < s.length(); i++) {
if (wordDict.contains(s.substring(0, i + 1))) {
map.put(s,process2(s.substring(i + 1),wordDict,map));
res = res || map.get(s);
}
}
return res;
}
}
动态规划
- 记忆化搜索并没有各个状态之间的依赖,先改写为动态规划。
- dp 数组的初始化状态为dp[0] = true,表示s为空串时应该返回true
public class WordBreak {
public boolean dpWay(String s, List<String> wordDict) {
int N = s.length();
boolean [] dp = new boolean[N + 1];
// 当s为空串时,应返回true
dp[0] = true;
// i = 1 表示当前只有一个字母
for (int i = 1; i < N + 1; i++) {
// 将s中0 - i位置的子串分为0-j 与 j-i
for (int j = 0; j < i; j++) {
// 若wordDict中包含s的j到i的字串,且当前dp数组dp[j] == true,则说明当前i位置为true
if (dp[j] == true && wordDict.contains(s.substring(j,i))) {
dp[i] = true;
break;
}
}
}
return dp[N];
}
}