一个旅行者有一个最多能装W千克的包,先有n种物品,每种物品的重量是W1,W2....Wn。求旅行者可装入最重物品的组合及组合数量!
分析:这是一道数学求组合的问题,也是最简单的背包算法,找出所有满足总重量的组合即可。
下面是我用java做出的解法
package com.test;
import java.util.ArrayList;
import java.util.List;
/**
* 简单背包算法
*
* @author taojinsha
*
*/
public class TestBag {
private int[] bags;
private int totalWeight;
private List<Object> result;
private List<Object> getBgsArrays(int[] bags, int totalWeight) {
this.bags = bags;
this.totalWeight = totalWeight;
result = new ArrayList<Object>();
initBags(0);
return result;
}
private void initBags(int depth) {
if (depth < bags.length - 1) {
getBags(depth + 1);
} else {
System.out.println("共有:" + result.size() + "种结果");
for (int i = 0; i < result.size(); i++) {
System.out.println(result.get(i));
}
}
}
/**
* 根据组合个数递归找到所有组合
* @param depth
*/
private void getBags(int depth) {
getCombinationsByLength(depth);
initBags(depth);
}
/**
* 求当前组合内的物品总重量
* @param v
* @return
*/
private int getTotal(List<Integer> v) {
int total = 0;
for (int i = 0; i < v.size(); i++) {
total += v.get(i);
}
return total;
}
public void getCombinationsByLength(int length) {
List<Integer> newData = new ArrayList<Integer>();
for (int i : bags) {
newData.add(i);
}
List<Integer> initialCombination = new ArrayList<Integer>();
combination(newData, initialCombination, length);
}
/**
* 利用递归算法求组合
* @param data
* @param initialCombination
* @param length
*/
private void combination(List<Integer> data,
List<Integer> initialCombination, int length) {
if (length == 1) {
for (int i = 0; i < data.size(); i++) {
List<Integer> newCombination = cloneList(initialCombination);
newCombination.add(data.get(i));
if (getTotal(newCombination) == totalWeight) {//当组合总重量满足背包最大重量时
result.add(newCombination);
}
}
}
if (length > 1) {
for (int i = 0; i < data.size(); i++) {
List<Integer> newCombination = cloneList(initialCombination);
newCombination.add(data.get(i));
List<Integer> newData = cloneList(data);
for (int j = 0; j <= i; j++) {
if (j < data.size()) {
newData.remove(data.get(j));
}
}
combination(newData, newCombination, length - 1);
}
}
}
private List<Integer> cloneList(List<Integer> data) {
List<Integer> newData = new ArrayList<Integer>();
for (Integer str : data) {
newData.add(str);
}
return newData;
}
public static void main(String args[]) {
int[] bags = { 15, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 13 };
int totalWeight = 20;
TestBag tb = new TestBag();
tb.getBgsArrays(bags, totalWeight);
}
}