[每日一刷] (Burst Balloon)
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.
Find the maximum coins you can collect by bursting the balloons wisely.
Example:
Given [3, 1, 5, 8]
Return 167
解题思路
看到maximum coins, 发现是一道求最优解的题,马上想到使用动态规划
本题的最优子结构是opt[i~j] = opt[i~k-1] + score[k] + opt[k+1~j], 其中k指的是最后一个爆破的气球的位置
本题的trick在于在算最优子结构的时候要在两边多算一个位置。例如算opt[1,2]的时候要将0, 3都算进去
代码虽然在leetcode上超时了,不过同样的做法使用JAVA和C++却可以通过,可能还是因为Python太慢了吧-.-
Python: