背包问题。。。

public static void main(String[] args) {
    int[] wight = {1, 4, 5, 2, 3};
    int[] value = {4, 1, 7, 5, 8};
    int num = 13;
    int max = compute(wight, value, num);
    System.out.println(max);
}

private static int compute(int[] wight, int[] value, int num) {
    int[][] mArray = new int[value.length][num];
    for (int j = 0; j < num; j++) {
        mArray[0][j] = value[0] > num ? 0 : value[0];
    }
    for (int i = 1; i < value.length; i++) {
        for (int j = 0; j < num; j++) {
            if (j - wight[i] >= 0) {
                mArray[i][j] = value[i] + mArray[i - 1][j - wight[i]];
            } else {
                mArray[i][j] = mArray[i - 1][j];
            }
        }
    }
    return mArray[value.length - 1][wight.length - 1];
}

构建二位象限,横轴背包最大容量,纵轴商品数据

你可能感兴趣的:(java,算法,数据结构)