编辑代码



public class BagProblem {


    public static void main(String[] args) {
        Product[] products = init();
        bagProblem(products,20);
        bagProblem(products,30);
        bagProblem(products,10);
    }

    /**
     *
     * @param products: 可选择的物品
     * @param target:背包可装的重量
     */
    public static void bagProblem(Product[] products, int target) {
        int maxweight=0;
        int maxprice=0;
        for (int i = 0; i < 8; i++) {
            int weight = 0;             //用来记录每种选择的重量和价格
            int price = 0;
            int j = i;                  //记录当前选择是否小于0,是的话就证明后面的物品没选就不再计算
            int z = products.length-1;  //记录当前正在计算的是哪个产品,用于取数组products的下标
            while (j>0){
                if((j&1)==1){
                    weight+=products[z].weight;
                    price+=products[z].price;
                }
                j>>=1;                  //向右移一位
                z--;
            }
            if(weight<=target&&price>maxprice){
                maxprice = price;
                maxweight = weight;
            }
        }

        System.out.println("背包重量是"+target+"的背包,最优价格:"+maxprice+";重量:"+maxweight);
    }

    private static Product[] init() {
        Product[] products = new Product[3];
        products[0] = new Product("电脑", 5, 2000);
        products[1] = new Product("手机", 5, 500);
        products[2] = new Product("平板", 15, 1000);
        return products;
    }
}

class Product {
    String name;
    int weight;
    int price;

    public Product(String name, int weight, int price) {
        this.name = name;
        this.weight = weight;
        this.price = price;
    }

    public Product(int weight, int price) {
        this.weight = weight;
        this.price = price;
    }

    public int getWeight() {
        return weight;
    }

    public void setWeight(int weight) {
        this.weight = weight;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}