Leetcode 312. Burst Balloons[hard]

来源:互联网 发布:直播音效软件下载 编辑:程序博客网 时间:2024/06/06 20:58

题目:
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


虽然leetcode标记是hard,但其实就是一个最简单的区间dp。
dp[i][j]表示戳爆i-j所能得到的最高分,则状态转移方程为:
dp[lt][rt] = max(dp[lt][rt], dp[lt][ i - 1] + dp[i + 1][rt] + v[i] * v[lt - 1] * v[rt + 1])
采用记忆化搜索实现。

这里写图片描述

class Solution {public:    vector<int> v;    int dp[510][510];    bool vis[510][510];    int maxCoins(vector<int>& nums) {        v.clear();        v.push_back(1);        for (int i = 0; i < nums.size(); i++) {            v.push_back(nums[i]);        }        v.push_back(1);        memset(vis, 0, sizeof vis);        dp[1][nums.size()] = calc(1, nums.size());        return dp[1][nums.size()];    }    int calc(int lt, int rt) {        if (lt > rt) return 0;        if (vis[lt][rt]) return dp[lt][rt];        if (lt == rt) {            vis[lt][lt] = true;            return dp[lt][lt] = v[lt - 1] * v[lt] * v[lt + 1];         }        dp[lt][rt] = calc(lt + 1, rt) + v[lt - 1] * v[lt] * v[rt + 1];        for (int i = lt + 1; i <= rt; i++) {            dp[lt][rt] = max(dp[lt][rt], calc(lt, i - 1) + calc(i + 1, rt) + v[i] * v[lt - 1] * v[rt + 1]);        }        vis[lt][rt] = true;        return dp[lt][rt];    }};
0 0
原创粉丝点击