From 1739379b3d31dfe41b519ee4f2eca3da03e53b79 Mon Sep 17 00:00:00 2001 From: ZongqinWang <1722249371@qq.com> Date: Sun, 19 Jun 2022 21:57:51 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200416.=E5=88=86=E5=89=B2?= =?UTF-8?q?=E7=AD=89=E5=92=8C=E5=AD=90=E9=9B=86.md=20Scala=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0416.分割等和子集.md | 55 +++++++++++++++++++++++++---- 1 file changed, 49 insertions(+), 6 deletions(-) diff --git a/problems/0416.分割等和子集.md b/problems/0416.分割等和子集.md index eb6601e1..e14287e6 100644 --- a/problems/0416.分割等和子集.md +++ b/problems/0416.分割等和子集.md @@ -183,7 +183,7 @@ public: ## 其他语言版本 -Java: +### Java: ```Java class Solution { public boolean canPartition(int[] nums) { @@ -316,7 +316,7 @@ class Solution { } } ``` -Python: +### Python: ```python class Solution: def canPartition(self, nums: List[int]) -> bool: @@ -329,7 +329,7 @@ class Solution: dp[j] = max(dp[j], dp[j - nums[i]] + nums[i]) return target == dp[target] ``` -Go: +### Go: ```go // 分割等和子集 动态规划 // 时间复杂度O(n^2) 空间复杂度O(n) @@ -397,7 +397,7 @@ func canPartition(nums []int) bool { } ``` -javaScript: +### javaScript: ```js var canPartition = function(nums) { @@ -417,7 +417,7 @@ var canPartition = function(nums) { ``` -C: +### C: 二维dp: ```c /** @@ -518,7 +518,7 @@ bool canPartition(int* nums, int numsSize){ } ``` -TypeScript: +### TypeScript: > 一维数组,简洁 @@ -573,7 +573,50 @@ function canPartition(nums: number[]): boolean { }; ``` +### Scala +滚动数组: +```scala +object Solution { + def canPartition(nums: Array[Int]): Boolean = { + var sum = nums.sum + if (sum % 2 != 0) return false + var half = sum / 2 + var dp = new Array[Int](half + 1) + + // 遍历 + for (i <- 0 until nums.length; j <- half to nums(i) by -1) { + dp(j) = math.max(dp(j), dp(j - nums(i)) + nums(i)) + } + + if (dp(half) == half) true else false + } +} +``` + +二维数组: +```scala +object Solution { + def canPartition(nums: Array[Int]): Boolean = { + var sum = nums.sum + if (sum % 2 != 0) return false + var half = sum / 2 + var dp = Array.ofDim[Int](nums.length, half + 1) + + // 初始化 + for (j <- nums(0) to half) dp(0)(j) = nums(0) + + // 遍历 + for (i <- 1 until nums.length; j <- 1 to half) { + if (j - nums(i) >= 0) dp(i)(j) = nums(i) + dp(i - 1)(j - nums(i)) + dp(i)(j) = math.max(dp(i)(j), dp(i - 1)(j)) + } + + // 如果等于half就返回ture,否则返回false + if (dp(nums.length - 1)(half) == half) true else false + } +} +``` -----------------------