LeetCode Algorithm部分.312
【312】Burst Balloons
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] ≤ 100Example:
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
经分析,此题大意是有n个气球按一定顺序排列,每个气球上有个数字,刺破第i个气球就会得到num[i-1] * num[i] * num[i+1]个硬币,num[i]是第i个气球上的数字,求最多能得到多少个硬币。
首先,我想的是把所有可能算出来,求最大,这时复杂度大约为O(n!),所以这种算法是不可取的。所以我试图用分治法来做。然而简单的二分的话,是会受到二分处两边元素的影响,显然不符合分治法的思想(因为此处会造成每个子问题会相互影响,这时可以用动态规划)然而假如我们倒过来看,以最后一个气球为界限的话,两边就不会相互影响了(因为那是最后才刺破的,两边的在之前已经刺破)。
所以此题可以用分治法(divide and conquer)或者动态规划(dynamic programming)
下面我就先用分治法
int divid(vector<int>& nums, vector<vector<int>>& dp, int left, int right)
{
if(left+1 == right) return 0;
if(dp[left][right] > 0) return dp[left][right];
int sum = 0;
for(int i = left+1; i < right; i++){
sum=max(sum, nums[left] * nums[i] * nums[right] + divid(nums, dp, left, i) + divid(nums, dp, i, right));
}//判断并计算在该区间哪个气球处最后刺破
dp[left][right] = sum;
return sum;
}
int maxCoins(vector<int>& nums) {
nums.insert(nums.begin(), 1);//头置1
nums.insert(nums.end(), 1);//尾置1
vector<vector<int>> dp(nums.size()+1, vector<int>(nums.size()+1, 0));//初始化,用于储存两数之间的答案
return divid(nums, dp, 0, nums.size()-1);
}