01背包问题

给定 n 件物品,每一个物品的重量为 w[n],每个物品的价值为 v[n]。现挑选物品放入背包中,假定背包能承受的最大重量为 capacity,求装入物品的最大价值是多少?

1.递归

public class Main {

    static int[] w = {2, 3, 4, 5};
    static int[] v = {3, 4, 5, 6};
    static int capacity = 8;
    public static void main(String[] args) {
        System.out.println(test(0,0));
    }
    static int test(int index,int weight){
        if (index >= 4) return 0;
        if (capacity < weight + w[index]) return 0 ;

        return Math.max(v[index] + test(index + 1,weight + w[index]),test(index + 1,weight));
    }
}

2.动态规划

看不懂,寄

posted @ 2022-05-05 17:27  学不会啊学不会  阅读(22)  评论(0)    收藏  举报