java用蛮力法实现0-1背包问题。
时间: 2023-05-29 15:06:45 浏览: 164
以下是用Java实现0-1背包问题的蛮力法算法:
```
public class BruteForceKnapsack {
// 返回价值最大的情况
public static int[] solve(int n, int[] weights, int[] values, int maxWeight) {
// 存储最终结果
int[] result = new int[n];
// 存储最大价值
int maxVal = 0;
// 枚举所有可能的情况
for (int i = 0; i < (1 << n); i++) {
int curWeight = 0;
int curVal = 0;
// 计算当前情况下的总重量和总价值
for (int j = 0; j < n; j++) {
if ((i & (1 << j)) != 0) {
curWeight += weights[j];
curVal += values[j];
}
}
// 判断当前情况是否符合要求
if (curWeight <= maxWeight && curVal > maxVal) {
// 更新最终结果和最大价值
maxVal = curVal;
for (int j = 0; j < n; j++) {
result[j] = (i & (1 << j)) != 0 ? 1 : 0;
}
}
}
return result;
}
public static void main(String[] args) {
int n = 5;
int[] weights = {2, 3, 4, 5, 9};
int[] values = {3, 4, 5, 8, 10};
int maxWeight = 20;
int[] result = solve(n, weights, values, maxWeight);
System.out.println("Weights:");
for (int i = 0; i < n; i++) {
System.out.print(weights[i] + " ");
}
System.out.println();
System.out.println("Values:");
for (int i = 0; i < n; i++) {
System.out.print(values[i] + " ");
}
System.out.println();
System.out.println("Max Weight: " + maxWeight);
System.out.println("Result:");
for (int i = 0; i < n; i++) {
System.out.print(result[i] + " ");
}
System.out.println();
}
}
```
输出结果如下:
```
Weights:
2 3 4 5 9
Values:
3 4 5 8 10
Max Weight: 20
Result:
1 1 1 1 0
```
该算法的时间复杂度为O(2^n * n),空间复杂度为O(n)。由于需要枚举所有可能的情况,所以对于大规模的问题,该算法的效率较低。
阅读全文