题目链接:https://leetcode.com/problems/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]
≤ 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
思路:考虑分治法来处理的时候,如果选择以某个气球为分割点,那么其左边部分和右边部分都要依赖与那个气球,因此我们不能让这个气球先爆.也就是说我们选择分割点的时候不是选择先爆的气球,而是最后爆的气球,这样分成的左右两个部分将相互独立.即如果最后只剩下气球i,那么其最后只依赖与第0和n-1个气球,而在[0, i] 和 [i, n-1]两个区间是相互独立的,这样我们就可以将问题分割为相互独立的子集.这样时间复杂为O(n^n). 但是在枚举各个分割点的时候会有很多重复的计算,因此我们可以保存已经计算过的区间.这样时间复杂度可以优化到O(n^3).
同样我们也可以使用动态规划来处理,其原理和分治一样,也是分区间由小到大最后完成整个计算.
两种代码如下:
class Solution { public: int divid(vector<int>& nums, vector<vector<int>>& dp, int low, int high) { if(low+1 == high) return 0; if(dp[low][high] > 0) return dp[low][high]; int ans = 0; for(int i = low+1; i < high; i++) ans=max(ans, nums[low]*nums[i]*nums[high] + divid(nums, dp, low, i) + divid(nums, dp, i, high)); dp[low][high] = ans; return ans; } int maxCoins(vector<int>& nums) { nums.insert(nums.begin(), 1); nums.insert(nums.end(), 1); vector<vector<int>> dp(nums.size()+1, vector<int>(nums.size()+1, 0)); return divid(nums, dp, 0, nums.size()-1); } };
class Solution { public: int maxCoins(vector<int>& nums) { nums.insert(nums.begin(), 1); nums.insert(nums.end(), 1); vector<vector<int>> dp(nums.size(), vector<int>(nums.size(), 0)); for(int i = 2; i< nums.size(); i++)//区间长度 for(int j = 0; j < nums.size()-i; j++)//区间起点 for(int k =j+1; k < i+j; k++)//起点和终点之间的点 dp[j][j+i] = max(dp[j][j+i], nums[j]*nums[k]*nums[j+i] + dp[j][k] + dp[k][j+i]); return dp[0][nums.size()-1]; } };