动态规划

0-1背包问题

自己实现的0-1背包问题的动态规划解法,先贴上吧,动态规划原理解释有空再写。


public static int[][] dynamicProgramming(int capacity, int[] weight, int[] value) {
        int[][] result = new int[weight.length + 1][capacity + 1];
        for (int i = 1; i < result.length; i++) {
            for (int j = 1; j < result[i].length; j++) {
                if (weight[i - 1] > j) {
                    result[i][j] = result[i - 1][j];
                } else {
                    int addition = result[i - 1][j - weight[i - 1]] + value[i - 1];
                    if (addition > result[i - 1][j]) {
                        result[i][j] = addition;
                    } else {
                        result[i][j] = result[i - 1][j];
                    }
                }
            }
        }
        return result;
    }

你可能感兴趣的:(动态规划)