1 题目
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.
Note:
(1) You may imagine nums[-1] = nums[n] = 1
. They are not real therefore you can not burst them.
(2) 0 ≤ n
≤ 500, 0 ≤ nums[i]
≤ 100
Example:
Given [3, 1, 5, 8]
Return 167
2 分析
用dp[i][j]存储从ij最大的coin数
在数组的前后添加1
确定左边界、右边界,枚举出长度为len(从3开始)的所有可能coin数
以最后一个被戳破的气球为界,将数组分为左右两边
状态方程如代码所示
3 C++ 实现
class Solution {
public:
int maxCoins(vector<int>& nums) {
nums.insert(nums.begin(), 1);
nums.push_back(1);
int n = nums.size();
int dp[n][n] = {};
for (int len = 3; len <= n; len++)
for (int l = 0; l <= n - len; l++) {
int r = l + len - 1;
for (int i = l + 1; i < r; i++)
dp[l][r] = max(dp[l][r],
nums[l] * nums[i] * nums[r] + dp[l][i] + dp[i][r]);
}
return dp[0][n - 1];
}
};