Leetcode 312. Burst Balloons

来源:互联网 发布:辐射4捏脸数据 美女 编辑:程序博客网 时间:2024/06/05 18:41

题目:

Given n balloons, indexed from 0 to n-1. Each balloon is painted with a number on it represented by arraynums. You are asked to burst all the balloons. If the you burst ballooni you will get nums[left] * nums[i] * nums[right] coins. Hereleft and right are adjacent indices of i. After the burst, theleft and right then becomes adjacent.

Find the maximum coins you can collect by bursting the balloons wisely.

思路:

将大问题分割成小问题,对于[a1,a2,a3,a4,a5,a6,......,an],将分割成两个子整体,分割点为k,则得到 N1 = [a1,a2,a3,....,a(k-1)], N2 = [a(k+1),a(k+2),.....,an]。这里分割点k的意义是踩破了第k个气球。于是把整体分成了两部分,问题在于,根据计算规则,k气球破了之后,a(k-1)和a(k+1)会变成相邻的,如果此时踩a(k-1)或者a(k+1),则都会收到另一个子整体的影响,这样的话,两个子问题就不独立了。

所以设k为对于整体N,最后一个被破掉的气球。那么在k被弄破之前,k左边及右边并不会相互影响,于是就成功构造出子问题。

状态转移方程为:dp[left][right] = max(dp[left][right], dp[left][i] + nums[left] * nums[i] * nums[right] + dp[i][right]);

其中 left<i<right , dp[left][right]即为当前子问题:第left和第right之间位置的气球的maxcoin。

当然,要将nums的头和尾分别加上一个元素1。

具体代码如下:

代码:

C++实现

class Solution {public:    int maxCoins(vector<int>& nums) {        nums.insert(nums.begin(), 1);        nums.push_back(1);        int n = nums.size();        int dp[n][n] = {};        for (int k = 2; k < n; k ++){            for (int left = 0; left < n - k; left ++){                int right = left + k;                for (int i = left + 1; i < right; i ++){                    dp[left][right] = max(dp[left][right], dp[left][i] + nums[left] * nums[i] * nums[right] + dp[i][right]);                }            }        }        return dp[0][n-1];    }};


0 0
原创粉丝点击