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];
}
};
本文介绍了一个名为BurstBalloons的问题,并详细解释了如何使用动态规划算法来解决这一难题。通过设立一个二维数组result[i][j]来记录踩爆两个气球之间可以获得的最大硬币数,最终实现求取最大收益。
&spm=1001.2101.3001.5002&articleId=59646193&d=1&t=3&u=0acf328e4bdf471aa280528b2cab9a34)

被折叠的 条评论
为什么被折叠?



