背包问题java 代码

背包问题,http://www.cnblogs.com/sdjl/articles/1274312.html 这篇文章介绍很详细,参照它的思路写了0/1背包问题代码。
package niukewang_jianzhiOffer;

/**
 * Created by zhangwenjie05 on 16/9/10.
 */
public class PakageQuestion {
    //物体的重
    static int weight[] = {2, 3, 1, 4, 6, 5};
    //物体的价值
    static int value[] = {5, 6, 5, 1, 19, 7};
    // maxValue[i][j]保存容量为I的背包从j个物体中选择最大价值的物体放入后最大的价值和
    static int maxValue[][] = new int[11][6];

    public static void main(String args[]) {
        // 初始化 -1表示没有存储值
        for (int i = 0; i < 11; i++)
            for (int j = 0; j < 6; j++) {
                maxValue[i][j] = -1;
            }
        //包容量10,有5个物体的最大价值
        int r = maxValue(10, 5);
        System.out.println("最大价值:"+r);
        int total = 10;
        //打印输出选取了那几个物体
        for (int j = 5; j > 0; j--) {
            if (maxValue[total][j] > maxValue[total][j - 1]) {
                System.out.println("选择" + j);
                total = total - weight[j];
                if (total == 0) break;
            }
        }
        if (total > weight[0]) System.out.println("选择" + 0);
    }

    // 容量和第几个物体
    private static int maxValue(int capacity, int count) {
        int mValue;
        // 不等于-1 表示已经计算过。直接取值
        if (maxValue[capacity][count] != -1) {
            mValue = maxValue[capacity][count];
        } else if (count == 0) { // 放进第一个物体;
            if (capacity > weight[0]) {
                mValue = value[0];
            } else {
                mValue = 0;
            }
        } else if (capacity >= weight[count]) {

            if (maxValue(capacity - weight[count], count - 1) + value[count] > maxValue(capacity, count - 1)) {
                mValue = maxValue(capacity - weight[count], count - 1) + value[count];
            } else {
                mValue = maxValue(capacity, count - 1);
            }

        } else {
            mValue = maxValue(capacity, count - 1);
        }
        maxValue[capacity][count] = mValue;
        return mValue;
    }

}

你可能感兴趣的:(Java)