mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 19:44:45 +08:00
添加 1049.最后一块石头的重量II.md Scala版本
This commit is contained in:
@ -152,7 +152,7 @@ public:
|
||||
## 其他语言版本
|
||||
|
||||
|
||||
Java:
|
||||
### Java:
|
||||
|
||||
一维数组版本
|
||||
```Java
|
||||
@ -212,7 +212,7 @@ class Solution {
|
||||
|
||||
```
|
||||
|
||||
Python:
|
||||
### Python:
|
||||
```python
|
||||
class Solution:
|
||||
def lastStoneWeightII(self, stones: List[int]) -> int:
|
||||
@ -225,7 +225,7 @@ class Solution:
|
||||
return sumweight - 2 * dp[target]
|
||||
```
|
||||
|
||||
Go:
|
||||
### Go:
|
||||
```go
|
||||
func lastStoneWeightII(stones []int) int {
|
||||
// 15001 = 30 * 1000 /2 +1
|
||||
@ -254,7 +254,7 @@ func max(a, b int) int {
|
||||
}
|
||||
```
|
||||
|
||||
JavaScript版本
|
||||
### JavaScript
|
||||
|
||||
```javascript
|
||||
/**
|
||||
@ -277,7 +277,7 @@ var lastStoneWeightII = function (stones) {
|
||||
};
|
||||
```
|
||||
|
||||
TypeScript:
|
||||
### TypeScript:
|
||||
|
||||
```typescript
|
||||
function lastStoneWeightII(stones: number[]): number {
|
||||
@ -296,7 +296,47 @@ function lastStoneWeightII(stones: number[]): number {
|
||||
};
|
||||
```
|
||||
|
||||
### Scala
|
||||
|
||||
滚动数组:
|
||||
```scala
|
||||
object Solution {
|
||||
def lastStoneWeightII(stones: Array[Int]): Int = {
|
||||
var sum = stones.sum
|
||||
var half = sum / 2
|
||||
var dp = new Array[Int](half + 1)
|
||||
|
||||
// 遍历
|
||||
for (i <- 0 until stones.length; j <- half to stones(i) by -1) {
|
||||
dp(j) = math.max(dp(j), dp(j - stones(i)) + stones(i))
|
||||
}
|
||||
|
||||
sum - 2 * dp(half)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
二维数组:
|
||||
```scala
|
||||
object Solution {
|
||||
def lastStoneWeightII(stones: Array[Int]): Int = {
|
||||
var sum = stones.sum
|
||||
var half = sum / 2
|
||||
var dp = Array.ofDim[Int](stones.length, half + 1)
|
||||
|
||||
// 初始化
|
||||
for (j <- stones(0) to half) dp(0)(j) = stones(0)
|
||||
|
||||
// 遍历
|
||||
for (i <- 1 until stones.length; j <- 1 to half) {
|
||||
if (j - stones(i) >= 0) dp(i)(j) = stones(i) + dp(i - 1)(j - stones(i))
|
||||
dp(i)(j) = math.max(dp(i)(j), dp(i - 1)(j))
|
||||
}
|
||||
|
||||
sum - 2 * dp(stones.length - 1)(half)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
-----------------------
|
||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||
|
Reference in New Issue
Block a user