贪心算法01背包问题代码
时间: 2023-11-21 22:53:22 浏览: 43
01背包问题是一个经典的动态规划问题,不过也可以使用贪心算法来解决。贪心算法的思想是每次选择当前最优的解,从而得到全局最优解。对于01背包问题,可以按照物品的单位重量价值进行排序,然后依次选择单位重量价值最高的物品放入背包中,直到背包装满或者所有物品都被选择完为止。
以下是Java实现贪心算法解决01背包问题的代码:
```
import java.util.Arrays;
public class KnapsackProblem {
public static void main(String[] args) {
int[] weights = {2, 3, 4, 5};
int[] values = {3, 4, 5, 6};
int capacity = 8;
double maxValue = knapsack(weights, values, capacity);
System.out.println("The maximum value of items that can be carried is: " + maxValue); }
public static double knapsack(int[] weights, int[] values, int capacity) {
int n = weights.length;
double[] unitValues = new double[n];
for (int i = 0; i < n; i++) {
unitValues[i] = (double) values[i] / weights[i];
}
Item[] items = new Item[n];
for (int i = 0; i < n; i++) {
items[i] = new Item(weights[i], values[i], unitValues[i]);
}
Arrays.sort(items);
double maxValue = 0;
for (int i = 0; i < n && capacity > 0; i++) {
if (items[i].weight <= capacity) {
maxValue += items[i].value;
capacity -= items[i].weight;
} else {
maxValue += capacity * items[i].unitValue;
capacity = 0;
}
}
return maxValue;
}
static class Item implements Comparable<Item> {
int weight;
int value;
double unitValue;
public Item(int weight, int value, double unitValue) {
this.weight = weight;
this.value = value;
this.unitValue = unitValue;
}
@Override
public int compareTo(Item other) {
return Double.compare(other.unitValue, this.unitValue);
}
}
}
```