mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 19:44:45 +08:00
添加 0416.分割等和子集.md Scala版本
This commit is contained in:
@ -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
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
-----------------------
|
||||
|
Reference in New Issue
Block a user