Burst Balloons(Hard)
Description
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
Analysis
这道题真的好难啊!错了无数遍。= =
题目的意思其实就是通过设定踩爆的气球的顺序来获得最多的硬币数。由于这个题目的分组是在分治算法上,所以这个题肯定是要用分治算法的。
但后来发现这道题需要采用动态规划的思想。通过设立一个二维数组result[i][j]来表示踩爆两个气球之间的可以获得的最大硬币数。最后返回result[0][n-1]来表示结果。注意一个点是可以利用最后一个被踩爆的气球来将问题分为两个独立的子问题来计算。
Code
class Solution {
public:
int maxCoins(vector<int>& nums) {
int n = nums.size() + 2;
int result[n][n] ;
for(int i = 0 ; i < n;++i){
for(int j = 0 ;j <n;++j){
result[i][j] = 0;
}
}
int arr[n] ;
arr[0] = 1 ;
arr[n-1] = 1 ;
for(int i = 1 ; i<n-1 ; ++ i){
arr[i] = nums[i - 1] ;
}
for(int k = 2 ; k < n; ++ k){
for(int i = 0 ; i < n - k ; ++ i ){
int j = i + k;
for(int l = i + 1 ; l < j ; ++ l){
result[i][j] = max(result[i][j] , arr[i]*arr[l]*arr[j] + result[i][l]+result[l][j]);
}
}
}
return result[0][n-1];
}
};