最近看了下背包问题的算法。顺便用scala写了下简单的实现
问题概述:现有一个只能承受limit重量的背包,放入一些物品,物品的重量和价值在List[(Int,Int)]中,如何是背包中物品最大价值
def bag(item: List[(Int, Int)], limit: Int): Int = item match {
case (weight, value) :: tail if (limit > 0 && limit >= weight) =>
math.max(bag(tail, limit), value + bag(tail, limit - weight))
case _ => 0
}
如果是求怎么组合。List[(Int,Int,Int)]表示(id,weight,value)的列表
def bag1(items: List[(Int, Int, Int)])(limit: Int): List[(Int, Int, Int)] = {
def valueOf(x: List[(Int, Int, Int)]) =
x.foldLeft(0)((sum, item) => sum + item._3)
def greater(left: List[(Int, Int, Int)], right: List[(Int, Int, Int)]) =
if (valueOf(left) > valueOf(right)) left else right
items match {
case (id, weight, value) :: tail if limit >= weight && limit > 0 =>
greater(bag1(tail)(limit), (id, weight, value) :: bag1(tail)(limit - weight))
case _ => Nil
}
}
效率可能不是最优(递归会消耗堆栈)的,但还算直观。
本文介绍了背包问题的经典算法,并提供了使用Scala语言实现的示例代码。通过对物品的价值和重量进行评估,该算法能够找到使背包装载价值最大的组合。
4412

被折叠的 条评论
为什么被折叠?



