Merge pull request #1487 from wzqwtt/dp04

添加(背包理论基础01背包-1、背包理论基础01背包-2) Scala版本
This commit is contained in:
程序员Carl
2022-07-28 09:45:43 +08:00
committed by GitHub
2 changed files with 60 additions and 0 deletions

View File

@ -502,7 +502,41 @@ const size = 4;
console.log(testWeightBagProblem(weight, value, size));
```
### Scala
```scala
object Solution {
// 01背包
def test_2_wei_bag_problem1(): Unit = {
var weight = Array[Int](1, 3, 4)
var value = Array[Int](15, 20, 30)
var baseweight = 4
// 二维数组
var dp = Array.ofDim[Int](weight.length, baseweight + 1)
// 初始化
for (j <- weight(0) to baseweight) {
dp(0)(j) = value(0)
}
// 遍历
for (i <- 1 until weight.length; j <- 1 to baseweight) {
if (j - weight(i) >= 0) dp(i)(j) = dp(i - 1)(j - weight(i)) + value(i)
dp(i)(j) = math.max(dp(i)(j), dp(i - 1)(j))
}
// 打印数组
dp.foreach(x => println("[" + x.mkString(",") + "]"))
dp(weight.length - 1)(baseweight) // 最终返回
}
def main(args: Array[String]): Unit = {
test_2_wei_bag_problem1()
}
}
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

View File

@ -375,7 +375,33 @@ console.log(testWeightBagProblem(weight, value, size));
```
### Scala
```scala
object Solution {
// 滚动数组
def test_1_wei_bag_problem(): Unit = {
var weight = Array[Int](1, 3, 4)
var value = Array[Int](15, 20, 30)
var baseweight = 4
// dp数组
var dp = new Array[Int](baseweight + 1)
// 遍历
for (i <- 0 until weight.length; j <- baseweight to weight(i) by -1) {
dp(j) = math.max(dp(j), dp(j - weight(i)) + value(i))
}
// 打印数组
println("[" + dp.mkString(",") + "]")
}
def main(args: Array[String]): Unit = {
test_1_wei_bag_problem()
}
}
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>