因此,如果您不了解背包问题是什么,这是一种从背包中提取不同重量的方法,以使它们加起来等于指定的总重量。这是我书中的示例,说明如果指定的总重量为20,如何解决问题。
如果有人知道如何使用PLEASE递归帮助在Java中实现此问题,我会感到困惑。这是我的开始,但是我很确定这是错误的,我不知道现在要去哪里。
import java.util.*;
public class n01044854 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please first enter a weight capacity up to a value of
100, followed by a series of individual weight values with 25 weights being the max.)
");
String values = input.nextLine();
String[] tokens = values.split(" +");
int capacity = Integer.parseInt(tokens[0]);
int[] weightValues = new int[tokens.length - 1];
for (int i = 0; i < tokens.length - 1; i++)
weightValues[i] = Integer.parseInt(tokens[i+1]);
optimizeWeights(capacity, weightValues, 0);
}
public static void optimizeWeights(int target, int[] weights, int currentIndex) {
if (weights[currentIndex] == target)
System.out.println("Success! Knapsack optimally filled.");
else if (weights[currentIndex] < target) {
int newTarget = target - weights[currentIndex];
optimizeWeights(newTarget, weights, currentIndex + 1);
} else if (weights[currentIndex] > target) {
if (currentIndex < weights.length - 1)
optimizeWeights(target, weights, currentIndex + 1);
else
//confused on what to do
}
}
}