public class ZeroOneBag {
static int value = 0, weight = 0, max = 0;
public static void main(String[] args) {
System.out.println(test());
}
private static int test() {
// int[] weights = {1, 3, 4};
// int[] weights = {2, 2, 3, 1, 5, 2};
// int[] values = {15, 20, 30};
// int[] values = {2, 3, 1, 5, 4, 3};
// return zeroOne(weights, values, 1);
// return zeroOne(weights, values, 4);
// int[] weights = {1};
// int[] values = {10};
// return zeroOne(weights, values, 1);
// int[] weights1 = {1, 2, 3};
// int[] values1 = {2, 3, 4};
// int bagWeight1 = 5;
// int[] weights2 = {2, 3, 4};
// int[] values2 = {3, 4, 5};
// int bagWeight2 = 6;
// int[] weights3 = {1, 3, 4, 5};
// int[] values3 = {1, 4, 5, 7};
// int bagWeight3 = 7;
int[] weights = {4,3,8,10,2};
int[] values = {6,2,10,4,1};
return zeroOne(weights, values, 10);
}
private static int zeroOne(int[] weights, int[] values, int bagWeight) {
backtracking(weights, values, bagWeight, 0);
return max;
}
private static void backtracking(int[] weights, int[] values, int bagWeight, int start) {
for (int i = start; i < weights.length; i++) {
if (weight + weights[i] > bagWeight) {
continue;
}
weight += weights[i];
value += values[i];
if (value > max) {
max = value;
}
backtracking(weights, values, bagWeight, i + 1);
weight -= weights[i];
value -= values[i];
}
}
}
01背包(回溯版)
最新推荐文章于 2024-09-29 08:33:21 发布