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 rightthen becomes adjacent.
Find the maximum coins you can collect by bursting the balloons wisely.
Note:
- You may imagine
nums[-1] = nums[n] = 1. They are not real therefore you can not burst them. - 0 ≤
n≤ 500, 0 ≤nums[i]≤ 100
Example:
1 | Input: [3,1,5,8] |
暴力搜索
第一步是最难的,需要确定暴力搜索的方法,保证能够搜索到所有可能的路径,通过比较所有可能的路径得到最优解。
之后,对暴力搜索进行优化,变成自顶向下的记忆化搜索,再变成自底向上,最后压缩空间。
自顶向下
1 | class Solution { |
AC代码2
1 | class Solution { |
自底向上
由解法2可得递推公式:
$$
f[i][j] = \max \limits_{i <= k <= j}{help[i-1]* help[k]*help[j+1] + f[i][k-1] + f[k+1][j]}
$$
另外,初值如下:
$$
f[i][i-1] = 0
$$
$$
1<=i<=n, 1<=j<=n
$$
其中,n为原数组nums的大小。但是这里的help是在原数组nums的最前面和最后面分别加上一个1形成的辅助数组。例如nums= [3,1,5,8],则help = [1, 3,1,5,8, 1] ,n = 4。
分析填表顺序
压缩空间
1 |