题目来源于:https://leetcode.com
312. Burst Balloons
- Total Accepted: 24690
- Total Submissions: 58469
- Difficulty: Hard
- Contributor: LeetCode
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
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
题解:
class Solution {
public:
vector<vector<int>> d;
int maxCoins(vector<int>& nums) {
if(nums.empty()){
return 0;
}
int size = nums.size();
nums.insert(nums.begin(), 1);
nums.insert(nums.end(), 1);
d = vector<vector<int>>(size + 2, vector<int>(size + 2, 0));
for(int len = 1; len <= size; ++len){
for(int start = 1;start + len - 1 <= size; ++start){
int end = start + len - 1;
for(int k = start;k <= end; ++k){// k is the last one to be popped
d[start][end] = max(d[start][end], d[start][k - 1] + d[k + 1][end] + nums[start - 1] * nums[k] * nums[end + 1]);
}
}
}
return d[1][size];
}
};