原题说明
We have a collection of rocks, each rock has a positive integer weight.
Each turn, we choose any two rocks and smash them together. Suppose the stones have weights x
and y
with x <= y
. The result of this smash is:
- If
x == y
, both stones are totally destroyed; - If
x != y
, the stone of weightx
is totally destroyed, and the stone of weighty
has new weighty-x
.
At the end, there is at most 1 stone left. Return the smallest possible weight of this stone (the weight is 0 if there are no stones left.)
Example 1:
Input: [2,7,4,1,8,1]
Output: 1
Explanation:
We can combine 2 and 4 to get 2 so the array converts to [2,7,1,8,1] then,
we can combine 7 and 8 to get 1 so the array converts to [2,1,1,1] then,
we can combine 2 and 1 to get 1 so the array converts to [1,1,1] then,
we can combine 1 and 1 to get 0 so the array converts to [1] then that’s the optimal value.
Note:
1 <= stones.length <= 30
1 <= stones[i] <= 100
解题思路
假设有三个石头x1,x2, x3
, 无论如何组合,最终都会成为三个数之间的加减法
比如如果先合并x1
,x2
,再与x3
合并,则最终的重量为x3 - x1 + x2
(假设x1 > x2, x3 > (x1 - x2)
)
所以这道题相当于将数组分为两组,两组分别求和为S1
和S2
,并希望其差值(S2 - S1 if S2 >= S1
)最小:S1 + S2 = total_weight
if S1 <= S2 => S2 - S1 = total_weight - S1 - S1 = total_weight - 2 * S1
所以相当于我们希望较小的一半石头的重量和尽可能接近 total_weight / 2
我们通过动态规划来求解这道题,建立一个数组dp
来记录石头重量之和的所有可能值:dp[i]
为true
如果我们可以使得一组stones
的重量之和S1
等于i
,反之则为false
我们遍历stones
数组,用sum_weight
来记录当前遍历到的所有重量之和,
我们判断加入当前的石头重量stone_weight
后,从sum_weight
到stone_weight
之间的每一个值weight
是否可能成为S1
的值:
如果dp[weight - stone_weight]
为true
,则对应的dp[weight]
也设为true
。
遍历stones
完成后,从weight = sum_weight / 2
开始逐渐减小,如果dp[weight] = true
,
则当前weight
即我们希望寻找的S1
的值,所以返回对应的total_weight - 2 * weight
即可。
示例代码 (cpp)
1 | class Solution { |
示例代码 (java)
1 | class Solution { |
示例代码 (python)
1 | class Solution: |
复杂度分析
时间复杂度: O(N)
空间复杂度: O(total_weight)
归纳总结
我们在Youtube上更新了视频讲解,欢迎关注!