最近在学习数据结构与算法这块,参考别人的代码,自己写了一遍回溯算法的01背包问题实现,记录一下,以备自己复习。
01背包指在背包可承受重量范围内的情况下,使得装入背包中物品的价值最大。
代码如下:
public class Backtrack01Knapsack {
public static int maxV = 0;
public static void main(String[] args) {
System.out.println("hello,world!");
//背包可承重大小
int bearing = 5;
//物品重量列表
int[] weights = {5,2,3,1,6,2,3};
//物品价值列表,与重量列表对应
int[] values = {8,6,5,3,12,7,6};
backtrace(0,0,0,bearing, weights, values);
System.out.println(maxV);
}
public static void backtrace(int i, int weight, int value, int bearing, int[] weights, int[] values) {
if(i == weights.length || weight == bearing) {
if(value > maxV) maxV = value;
return;
}
if(weight + weights[i] <= bearing) {
backtrace(i + 1, weight + weights[i], value + values[i], bearing, weights, values);
}
backtrace(i + 1, weight, value, bearing, weights, values);
}
}
运行结果:
hello,world!
16
结果对应重量列表中的:weights[1,3,5] = [2,1,2]
价值列表中的:values[1,3,5] = [6,3,7] = 16。