美文网首页
穷举法解决0/1背包问题

穷举法解决0/1背包问题

作者: 无酒之人 | 来源:发表于2018-09-29 18:07 被阅读0次

[0-1背包问题]有一个背包,背包容量是M=150kg。有7个物品,物品不可以分割成任意大小。(这句很重要)
要求尽可能让装入背包中的物品总价值最大,但不能超过总容量。
物品 A B C D E F G
重量 35kg 30kg 6kg 50kg 40kg 10kg 25kg
价值 10 40 30 50 35 40 30


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <script>
    console.time('计时器')
    const things = [
      {
        name: 'A',
        weight: 35,
        price: 10
      },{
        name: 'B',
        weight: 30,
        price: 40
      },{
        name: 'C',
        weight: 6,
        price: 30
      },{
        name: 'D',
        weight: 50,
        price: 50
      },{
        name: 'E',
        weight: 40,
        price: 35
      },{
        name: 'F',
        weight: 10,
        price: 40
      }, {
        name: 'G',
        weight: 25,
        price: 30
      }
    ],
    package = {
      things: [],
      maxWeight: 150
    }
let arr = []
for (let i=0; i<Math.pow(2, things.length); i++) {
  arr[i] = []
  let v = (i).toString(2).split('').reverse()
  things.forEach((el, index) => {
    if(v[index] === '1') {
      arr[i].push(el)
    }
  })
}
let newArr = arr.filter((el) => {
  let weight = 0
  el.forEach((el) => {
    weight += el.weight
  })
  return weight < package.maxWeight
})
newArr.sort((a, b) => {
  let price1 = 0,
  price2 = 0
  a.forEach((el) => {
    price1 += el.price
  })
  b.forEach((el) => {
    price2 += el.price
  })
  return price2 - price1
})
console.timeEnd('计时器')
console.log(newArr);
  </script>
</body>
</html>

相关文章

  • 穷举法解决0/1背包问题

    [0-1背包问题]有一个背包,背包容量是M=150kg。有7个物品,物品不可以分割成任意大小。(这句很重要)要求尽...

  • (python实现)购物单问题

    购物单问题实际上是0-1问题,在解决这个问题之前,要理解0-1背包问题。可以自己百度或者阅读我对0-1背包问题的理...

  • Algorithm进阶计划 -- 动态规划(下)

    经典动态规划背包问题最长子序列问题 1. 背包问题 1.1 0-1 背包问题 0-1 背包问题,描述如下: 上面...

  • LeetCode 动态规划专题 5:0-1 背包问题

    这一节我们介绍使用动态规划解决的一个非常经典的问题:0-1 背包问题。 0-1 背包问题描述 问题描述: 有一个背...

  • 背包问题

    背包问题属于典型的动态规划问题。这里我们将详细介绍0-1背包,完全背包和多重背包问题 一、 0-1背包 有N件物品...

  • 算法-动态规划-背包问题

    背包问题是基础的动态规划问题,包含了0-1背包,完全背包,多重背包等。 0-1背包 存在容量为 的背包 , 件体...

  • 0/1背包问题

    输出结果

  • 背包问题

    1、前言 背包问题是典型的动态规划问题,它有非常多的类型,本文讨论最常见的0-1背包问题 0-1背包问题描述:有一...

  • 0/1背包问题 0/1 Knapsack

    题目列表 相等子集划分问题 Equal Subset Sum Partition 416. 分割等和子集 子集和问...

  • 0-1背包问题(回溯法)

    0-1背包问题 在0 / 1背包问题中,需对容量为c 的背包进行装载。从n 个物品中选取装入背包的物品,每件物品i...

网友评论

      本文标题:穷举法解决0/1背包问题

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