题目
- 求背包能装下的物品组合
- 例如:给定物品重量,int[] arr = {1, 2, 3, 4, 5},背包能容纳的总重量为12,输出[1 2 3 4 ] 和 [3 4 5]
解法
/**
* 单一背包问题
*
* @param arr
* @param total
*/
public static void knapsackQuestion(int[] arr, int total) {
if (arr == null || arr.length < 0 || total < 0) return;
boolean[] selected = new boolean[arr.length];
knapsack(arr, selected, total, 0);
}
/**
* 找出符合承重重量的组合
*
* @param total 总重量
* @param index 可供选择的重量下标
*/
public static void knapsack(int[] arr, boolean[] selects, int total, int index) {
if (total < 0 || total > 0 && index >= arr.length) {
return; // 没找到解决办法,直接返回
}
// 总重量为0,则找到解决办法了
if (total == 0) {
for (int i = 0; i < index; i++) {
if (selects[i]) {
System.out.print(arr[i] + " ");
}
}
System.out.println();
return;
}
// 第一个合适
selects[index] = true;
knapsack(arr, selects, total - arr[index], index + 1);
// 沒有找到合适数据,重置,从第二个开始查找
selects[index] = false;
knapsack(arr, selects, total, index + 1);
}