美文网首页
动态规划(背包问题)

动态规划(背包问题)

作者: RalapHao | 来源:发表于2019-06-18 17:58 被阅读0次
    1. 记录局部最优解,作为下次求解的基础
    2. 重要公式
      w[i] > j: v[i][j] = v[i][j];
      w[i] <= j : v[i][j] = Math.max(v[i][j], v[i][j - w[i]] + val[i]);
    public class KnapsackProblem {
    
        public static void main(String[] args) {
            KnapsackProblem kp = new KnapsackProblem();
            kp.knapsack();
    
        }
    
        public void knapsack() {
            int[] w = {1, 4, 3};
            int[] val = {1500, 3000, 2000};
            int m = 4;
            int n = w.length;
            int[][] v = new int[n + 1][m + 1];
    
            for (int i = 0; i < v.length; i++) {
                v[i][0] = 0;
            }
    
            for (int i = 0; i < v[0].length; i++) {
                v[0][i] = 0;
            }
    
            for (int i = 1; i < v.length; i++) {
                for (int j = 1; j < v[0].length; j++) {
    
                    if (w[i - 1] > j) {
                        v[i][j] = v[i - 1][j];
                    } else {
                        v[i][j] = Math.max(v[i - 1][j], v[i - 1][j - w[i-1]] + val[i-1]);
                    }
                }
            }
            for (int i = 0; i < v.length; i++) {
                for (int j = 0; j < v[0].length; j++) {
                    System.out.print(v[i][j] + " ");
                }
                System.out.println();
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:动态规划(背包问题)

          本文链接:https://www.haomeiwen.com/subject/fqrqqctx.html