From c99bf39601a06278f9cca2e5f6d61638e23f3ced Mon Sep 17 00:00:00 2001 From: ZongqinWang <1722249371@qq.com> Date: Thu, 23 Jun 2022 21:34:24 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200474.=E4=B8=80=E5=92=8C?= =?UTF-8?q?=E9=9B=B6.md=20Scala=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0474.一和零.md | 83 +++++++++++++++++++++++++++++++++++--- 1 file changed, 78 insertions(+), 5 deletions(-) diff --git a/problems/0474.一和零.md b/problems/0474.一和零.md index d38ce03f..d6c598aa 100644 --- a/problems/0474.一和零.md +++ b/problems/0474.一和零.md @@ -163,7 +163,7 @@ public: ## 其他语言版本 -Java: +### Java ```Java class Solution { public int findMaxForm(String[] strs, int m, int n) { @@ -192,7 +192,7 @@ class Solution { } ``` -Python: +### Python ```python class Solution: def findMaxForm(self, strs: List[str], m: int, n: int) -> int: @@ -208,7 +208,7 @@ class Solution: return dp[m][n] ``` -Go: +### Go ```go func findMaxForm(strs []string, m int, n int) int { // 定义数组 @@ -294,7 +294,7 @@ func getMax(a,b int)int{ } ``` -Javascript: +### Javascript ```javascript const findMaxForm = (strs, m, n) => { const dp = Array.from(Array(m+1), () => Array(n+1).fill(0)); @@ -323,7 +323,7 @@ const findMaxForm = (strs, m, n) => { }; ``` -TypeScript: +### TypeScript > 滚动数组,二维数组法 @@ -446,7 +446,80 @@ function isValidSubSet(strs: string[], m: number, n: number): boolean { } ``` +### Scala +背包: +```scala +object Solution { + def findMaxForm(strs: Array[String], m: Int, n: Int): Int = { + var dp = Array.ofDim[Int](m + 1, n + 1) + + var (oneNum, zeroNum) = (0, 0) + + for (str <- strs) { + oneNum = 0 + zeroNum = 0 + for (i <- str.indices) { + if (str(i) == '0') zeroNum += 1 + else oneNum += 1 + } + + for (i <- m to zeroNum by -1) { + for (j <- n to oneNum by -1) { + dp(i)(j) = math.max(dp(i)(j), dp(i - zeroNum)(j - oneNum) + 1) + } + } + } + + dp(m)(n) + } +} +``` + +回溯法(超时): +```scala +object Solution { + import scala.collection.mutable + + var res = Int.MinValue + + def test(str: String): (Int, Int) = { + var (zero, one) = (0, 0) + for (i <- str.indices) { + if (str(i) == '1') one += 1 + else zero += 1 + } + (zero, one) + } + + def travsel(strs: Array[String], path: mutable.ArrayBuffer[String], m: Int, n: Int, startIndex: Int): Unit = { + if (startIndex > strs.length) { + return + } + + res = math.max(res, path.length) + + for (i <- startIndex until strs.length) { + + var (zero, one) = test(strs(i)) + + // 如果0的个数小于m,1的个数小于n,则可以回溯 + if (zero <= m && one <= n) { + path.append(strs(i)) + travsel(strs, path, m - zero, n - one, i + 1) + path.remove(path.length - 1) + } + } + } + + def findMaxForm(strs: Array[String], m: Int, n: Int): Int = { + res = Int.MinValue + var path = mutable.ArrayBuffer[String]() + travsel(strs, path, m, n, 0) + res + } +} +``` -----------------------