背包算法
import com.google.common.collect.Lists;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class BagAlgorithm {
private static List<Integer> weightList = Lists.newArrayList(1, 2, 3, 4, 5);
private static List<Integer> valueList = Lists.newArrayList(2, 3, 4, 5, 6);
private static Integer weightCapacity = 6;
public static List<Integer> getRemainedWightList(Integer allValue, Integer weightCapacity, List<Integer> indexRemovedList) {
List<Integer> valueCapacityList = Lists.newArrayList();
System.out.println(allValue + "::::" + weightCapacity + "::::::::" + indexRemovedList);
outer:
for (int i = 0; i < weightList.size(); i++) {
if (indexRemovedList.indexOf(i) != -1) {
continue outer;
}
Integer currWeight = weightList.get(i);
Integer currValue = currWeight * valueList.get(i);
/**
* 继续
*/
int remainedCapacity = weightCapacity - currWeight;
if (remainedCapacity > 0) {
indexRemovedList.add(i);
valueCapacityList.add(allValue + currValue);
valueCapacityList.addAll(getRemainedWightList(allValue + currValue, remainedCapacity, indexRemovedList));
} else if (remainedCapacity == 0) {
valueCapacityList.add(allValue + currValue);
return valueCapacityList;
} else {
return valueCapacityList;
}
}
return valueCapacityList;
}
public static void main(String[] args) {
List<Integer> newList = Lists.newArrayList();
for (int i = 0; i < weightList.size(); i++) {
newList.addAll(getRemainedWightList(weightList.get(i) * valueList.get(i), 6 - weightList.get(i), Lists.newArrayList(i)));
}
System.out.println(newList);
System.out.println(newList.stream().max(Comparator.comparingInt(Integer::valueOf)));
}
}
```