★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-tyvozdbm-me.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Given several boxes with different colors represented by different positive numbers.
You may experience several rounds to remove boxes until there is no box left. Each time you can choose some continuous boxes with the same color (composed of k boxes, k >= 1), remove them and get k*k
points.
Find the maximum points you can get.git
Example 1:
Input:github
[1, 3, 2, 2, 2, 3, 4, 3, 1]
Output:微信
23
Explanation:spa
[1, 3, 2, 2, 2, 3, 4, 3, 1] ----> [1, 3, 3, 4, 3, 1] (3*3=9 points) ----> [1, 3, 3, 3, 1] (1*1=1 points) ----> [1, 1] (3*3=9 points) ----> [] (2*2=4 points)
Note: The number of boxes n
would not exceed 100.code
給出一些不一樣顏色的盒子,盒子的顏色由數字表示,即不一樣的數字表示不一樣的顏色。
你將通過若干輪操做去去掉盒子,直到全部的盒子都去掉爲止。每一輪你能夠移除具備相同顏色的連續 k 個盒子(k >= 1),這樣一輪以後你將獲得 k*k
個積分。
當你將全部盒子都去掉以後,求你能得到的最大積分和。htm
示例 1:
輸入:blog
[1, 3, 2, 2, 2, 3, 4, 3, 1]
輸出:rem
23
解釋:get
[1, 3, 2, 2, 2, 3, 4, 3, 1] ----> [1, 3, 3, 4, 3, 1] (3*3=9 分) ----> [1, 3, 3, 3, 1] (1*1=1 分) ----> [1, 1] (3*3=9 分) ----> [] (2*2=4 分)
1 class Solution { 2 func removeBoxes(_ boxes: [Int]) -> Int { 3 var n:Int = boxes.count 4 var dp = [[[Int]]](repeating: [[Int]](repeating: [Int](repeating: 0, count: n), count: n), count: n) 5 for i in 0..<n 6 { 7 for k in 0...i 8 { 9 dp[i][i][k] = (1 + k) * (1 + k) 10 } 11 } 12 for t in 1..<n 13 { 14 for j in t..<n 15 { 16 var i:Int = j - t 17 for k in 0...i 18 { 19 var res:Int = (1 + k) * (1 + k) + dp[i + 1][j][0] 20 for m in (i + 1)...j 21 { 22 if boxes[m] == boxes[i] 23 { 24 res = max(res, dp[i + 1][m - 1][0] + dp[m][j][k + 1]) 25 } 26 } 27 dp[i][j][k] = res 28 } 29 } 30 } 31 return n == 0 ? 0 : dp[0][n - 1][0] 32 } 33 }