139 单词拆分
https://leetcode.cn/problems/word-break/description/
拆单词是有顺序的,要先遍历背包再遍历物品。
class Solution { //TO(n^2 * n(set.contains substring)), SO(n)
public boolean wordBreak(String input, List<String> dict) {
// array[i] represent whether or not the substring of input[0,1) can break
//Assumption: input not null nor empty, dict not null nor empty
boolean[] array = new boolean[input.length() + 1];
array[0] = true;
Set<String> set = toSet(dict);
for (int i = 1; i <= input.length(); i++) {
for (int j = 0; j < i; j++) {
if (array[j] == true && set.contains(input.substring(j, i))) { // subString begins at j, ends at i - 1
array[i] = true;
break;
}
}
}
return array[input.length()];
}
private Set<String> toSet(List<String> dict) {
Set<String> set = new HashSet<>();
for (String s : dict) {
set.add(s);
}
return set;
}
}
背包总结篇非常有用
https://programmercarl.com/%E8%83%8C%E5%8C%85%E6%80%BB%E7%BB%93%E7%AF%87.html
问能否能装满背包(或者最多装多少):dp[j] = max(dp[j], dp[j - nums[i]] + nums[i]); ,对应题目如下:
问装满背包有几种方法:dp[j] += dp[j - nums[i]] ,对应题目如下:
问背包装满最大价值:dp[j] = max(dp[j], dp[j - weight[i]] + value[i]); ,对应题目如下:
问装满背包所有物品的最小个数:dp[j] = min(dp[j - coins[i]] + 1, dp[j]); ,对应题目如下: