139.单词拆分
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
int len = s.length();
boolean[] dp = new boolean[len+1];
dp[0] = true;
for(int j = 1; j < len + 1; ++j) {
for(String i : wordDict) {
if(j >= i.length() && !dp[j] && i.equals(s.substring(j - i.length(), j))) {
dp[j] |= dp[j - i.length()];
}
}
}
return dp[len];
}
}
卡码网56. 携带矿石资源
题目链接:题目页面 (kamacoder.com)
方法一:一次只放入一个矿石,按照0-1背包问题实现,超时
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int c = sc.nextInt();
int n = sc.nextInt();
int[] weight = new int[n];
int[] value = new int[n];
int[] num = new int[n];
for(int i = 0; i < n; ++i) {
weight[i] = sc.nextInt();
}
for(int i = 0; i < n; ++i) {
value[i] = sc.nextInt();
}
for(int i = 0; i < n; ++i) {
num[i] = sc.nextInt();
}
sc.close();
int[] dp = new int[c + 1];
for(int i = 0; i < n;) {
for(int j = c; j >= weight[i]; --j) {
dp[j] = Math.max(dp[j],dp[j-weight[i]] + value[i]);
}
--num[i];
if(num[i] == 0) {
++i;
}
}
System.out.println(dp[c]);
}
}
方法二:一次性放多个同种矿石
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int c = sc.nextInt();
int n = sc.nextInt();
int[] weight = new int[n];
int[] value = new int[n];
int[] num = new int[n];
for(int i = 0; i < n; ++i) {
weight[i] = sc.nextInt();
}
for(int i = 0; i < n; ++i) {
value[i] = sc.nextInt();
}
for(int i = 0; i < n; ++i) {
num[i] = sc.nextInt();
}
sc.close();
int[] dp = new int[c + 1];
for(int i = 0; i < n;++i) {
for(int j = c; j >= weight[i]; --j) {
for(int k = 1; k <= num[i] && (j - k*weight[i]) >=0; ++k){
dp[j] = Math.max(dp[j],dp[j-k*weight[i]] + k*value[i]);
}
}
}
System.out.println(dp[c]);
}
}