添加 0416.分割等和子集.md Scala版本

This commit is contained in:
ZongqinWang
2022-06-19 21:57:51 +08:00
parent 630a3f80bf
commit 1739379b3d

View File

@ -183,7 +183,7 @@ public:
## 其他语言版本 ## 其他语言版本
Java ### Java
```Java ```Java
class Solution { class Solution {
public boolean canPartition(int[] nums) { public boolean canPartition(int[] nums) {
@ -316,7 +316,7 @@ class Solution {
} }
} }
``` ```
Python ### Python
```python ```python
class Solution: class Solution:
def canPartition(self, nums: List[int]) -> bool: def canPartition(self, nums: List[int]) -> bool:
@ -329,7 +329,7 @@ class Solution:
dp[j] = max(dp[j], dp[j - nums[i]] + nums[i]) dp[j] = max(dp[j], dp[j - nums[i]] + nums[i])
return target == dp[target] return target == dp[target]
``` ```
Go ### Go
```go ```go
// 分割等和子集 动态规划 // 分割等和子集 动态规划
// 时间复杂度O(n^2) 空间复杂度O(n) // 时间复杂度O(n^2) 空间复杂度O(n)
@ -397,7 +397,7 @@ func canPartition(nums []int) bool {
} }
``` ```
javaScript: ### javaScript:
```js ```js
var canPartition = function(nums) { var canPartition = function(nums) {
@ -417,7 +417,7 @@ var canPartition = function(nums) {
``` ```
C: ### C:
二维dp 二维dp
```c ```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
}
}
```
----------------------- -----------------------