★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-fnznsamx-kp.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Given n
balloons, indexed from 0
to n-1
. Each balloon is painted with a number on it represented by array nums
. You are asked to burst all the balloons. If the you burst balloon i
you will get nums[left] * nums[i] * nums[right]
coins. Here left
and right
are adjacent indices of i
. After the burst, the left
and right
then becomes adjacent.git
Find the maximum coins you can collect by bursting the balloons wisely.github
Note:數組
nums[-1] = nums[n] = 1
. They are not real therefore you can not burst them.n
≤ 500, 0 ≤ nums[i]
≤ 100Example:微信
Input: Output: nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> [] coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167[3,1,5,8]167 Explanation:
有 n
個氣球,編號爲0
到 n-1
,每一個氣球上都標有一個數字,這些數字存在數組 nums
中。spa
如今要求你戳破全部的氣球。每當你戳破一個氣球 i
時,你能夠得到 nums[left] * nums[i] * nums[right]
個硬幣。 這裏的 left
和 right
表明和 i
相鄰的兩個氣球的序號。注意當你戳破了氣球 i
後,氣球 left
和睦球 right
就變成了相鄰的氣球。code
求所能得到硬幣的最大數量。htm
說明:blog
nums[-1] = nums[n] = 1
,但注意它們不是真實存在的因此並不能被戳破。n
≤ 500, 0 ≤ nums[i]
≤ 100示例:get
輸入: 輸出: nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> [] coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167[3,1,5,8]167 解釋:
188 ms
1 class Solution { 2 func maxCoins(_ nums: [Int]) -> Int { 3 if nums.isEmpty { 4 return 0 5 } 6 if nums.count < 2 { 7 return nums[0] 8 } 9 let coinNums = [1] + nums + [1] 10 var coins = Array(repeating: Array(repeating: 0, count: coinNums.count), count: coinNums.count) 11 let count = coinNums.count 12 for i in 2..<count { 13 for j in 0..<count-i { 14 for k in j+1..<j+i { 15 coins[j][j+i] = max(coins[j][j+i],coins[j][k] + coins[k][j+i] + coinNums[k] * coinNums[j] * coinNums[j+i]) 16 } 17 } 18 } 19 20 return coins[0][coinNums.count-1] 21 } 22 }