★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(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 }