美文网首页
动态背包模式js实现

动态背包模式js实现

作者: 小强不是蟑螂啊 | 来源:发表于2019-04-03 15:32 被阅读0次
   function max(a, b) {
      return (a > b) ? a : b;
    }

   function bag(capacity, size, value, n) {
      var K = [];
      for (var i = 0; i <= capacity + 1; i++) {
        K[i] = [];
      }
      for (var i = 0; i <= n; i++) {
        for (var w = 0; w <= capacity; w++) {
          if (i == 0 || w == 0) {
            K[i][w] = 0;
          }
          else if (size[i - 1] <= w) {
            K[i][w] = max(value[i - 1] + K[i-1][w-size[i-1]],
            K[i-1][w]);
          }
          else {
            K[i][w] = K[i - 1][w];
          }
        }
      }
      console.log(K)
    }
    var value = [4, 5, 10, 11, 13];
    var size = [3, 4, 7, 8, 9];
    var capacity = 16;
    var n = 5;
    bag(capacity, size, value, n); 

相关文章

网友评论

      本文标题:动态背包模式js实现

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