【数据结构】动态规划--经典算法0-1背包问题

public class DynamicPlay {
    public static int pack(int[] item, int n, int totalWeight) {
        // 申请一个状态数组
        boolean[] state = new boolean[totalWeight + 1];
        // 哨兵作用
        state[0] = true;
        for (int i = 1; i < n; i++) {
            for (int j = totalWeight - item[i]; j >= 0; j--) {
                if (state[j]) {
                    state[j + item[i]] = true;
                }
            }
        }
        for (int i = totalWeight; i >= 0; i--) {
            if (state[i]) {
                return i;
            }
        }
        return 0;
    }

    public static int pack(int[] item, int[] value, int n, int totalWeight) {
        int[][] state = new int[n][totalWeight + 1];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < totalWeight + 1; j++) {
                state[i][j] = -1;
            }
        }
        // 一层层计算下来
        for (int i = 1; i < n; i++) {
            // 第n个不添加
            for (int j = 0; j <= totalWeight - item[i]; j++) {
                if (state[i - 1][j] != -1) {
                    state[i][j] = state[i - 1][j];
                }
            }
            for (int j = totalWeight - item[i]; j >= 0; j--) {
                int v = state[i - 1][j] + value[i];
                if (v > state[i][j + item[i]]) {
                    state[i][j + item[i]] = v;
                }
            }

        }
        int max = -1;
        for (int j = 0; j <= totalWeight; j++) {
            if (state[n - 1][j] > max) {
                max = state[n - 1][j];
            }
        }
        return max;

    }
}

 

你可能感兴趣的:(anddroid相关,java,设计框架)