From 106430d0083351c958e90745103747ea8fe7399e Mon Sep 17 00:00:00 2001 From: ZongqinWang <1722249371@qq.com> Date: Sun, 19 Jun 2022 21:20:49 +0800 Subject: [PATCH 1/2] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20=E8=83=8C=E5=8C=85?= =?UTF-8?q?=E7=90=86=E8=AE=BA=E5=9F=BA=E7=A1=8001=E8=83=8C=E5=8C=85-1.md?= =?UTF-8?q?=20Scala=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/背包理论基础01背包-1.md | 34 ++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/problems/背包理论基础01背包-1.md b/problems/背包理论基础01背包-1.md index a40a92ab..f9916667 100644 --- a/problems/背包理论基础01背包-1.md +++ b/problems/背包理论基础01背包-1.md @@ -498,7 +498,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() + } +} +``` -----------------------