今天用贪心算法给出背包问题的一种解,虽然贪心算法不一定是最优解,但是在数据量极大时,贪心算法可以快速获得接近最优解的答案

package test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Created by saishangmingzhu on 2018/11/26.
 */
public class Rucksack {
    //【1】输入背包容量
    //【2】输入物品体积及价值
    public static void main(String[] arg) {
        new Rucksack().greedy();
    }

    /**
     * 贪心算法
     */
    public void greedy(){
        int rucksackV=10;
        List goodsList=new ArrayList<>();
        goodsList.add(new Goods("书",1,2));
        goodsList.add(new Goods("足球",3,4));
        goodsList.add(new Goods("大箱子",7,2));
        goodsList.add(new Goods("macbook",3,6));
        goodsList.add(new Goods("iphone",1,5));
        goodsList.add(new Goods("礼盒",5,3));
        goodsList.add(new Goods("小箱子",4,2));
        //排序,价值大的排前边,相同情况下体积小的排前边
        Collections.sort(goodsList,new Comparator() {
            public int compare(Goods g1,Goods g2)
            {
                if (g1.getWorth()>g2.getWorth())
                    return -1;
                else if (g1.getWorth()g2.getVolume())
                        return 1;
                    else if (g1.getVolume()