★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-kdbxufyw-mc.html
➤若是连接不是山青咏芝的博客园地址,则多是爬取做者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持做者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
We have a collection of rocks, each rock has a positive integer weight.git
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:github
x == y
, both stones are totally destroyed;x != y
, the stone of weight x
is totally destroyed, and the stone of weight y
has new weight y-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:this
1 <= stones.length <= 30
1 <= stones[i] <= 100
有一堆石头,每块石头的重量都是正整数。spa
每一回合,从中选出任意两块石头,而后将它们一块儿粉碎。假设石头的重量分别为 x
和 y
,且 x <= y
。那么粉碎的可能结果以下:code
x == y
,那么两块石头都会被彻底粉碎;x != y
,那么重量为 x
的石头将会彻底粉碎,而重量为 y
的石头新重量为 y-x
。最后,最多只会剩下一块石头。返回此石头最小的可能重量。若是没有石头剩下,就返回 0
。htm
示例:blog
输入:[2,7,4,1,8,1] 输出:1 解释: 组合 2 和 4,获得 2,因此数组转化为 [2,7,1,8,1], 组合 7 和 8,获得 1,因此数组转化为 [2,1,1,1], 组合 2 和 1,获得 1,因此数组转化为 [1,1,1], 组合 1 和 1,获得 0,因此数组转化为 [1],这就是最优值。
提示:
1 <= stones.length <= 30
1 <= stones[i] <= 1000
1 class Solution { 2 let MAX:Int = 3005 3 func lastStoneWeightII(_ stones: [Int]) -> Int { 4 var possible:[Bool] = [Bool](repeating:false,count:2 * MAX + 1) 5 possible[MAX] = true 6 for stone in stones 7 { 8 var next_possible:[Bool] = [Bool](repeating:false,count:2 * MAX + 1) 9 for x in 0...2 * MAX 10 { 11 if possible[x] 12 { 13 14 next_possible[x + stone] = true 15 next_possible[x - stone] = true 16 } 17 } 18 possible = next_possible 19 } 20 for i in 0...MAX 21 { 22 if possible[MAX + i] 23 { 24 return i 25 } 26 } 27 return -1 28 } 29 }