LeetCode 312. Burst Balloons

LintCode 168. Burst Balloons

Posted by Olivia Liu on August 7, 2019 | 阅读:

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.

Answer

Using dynamic programming to solve this question.

Define a 2-dimensional matrix dp(nums.size(), nums.size()). dp[i][j] represents the maximum profit of bursting [i + 1,..., j - 1] balloons. Suppose k balloon (i + 1 <= k <= j - 1) is the last balloon burst among [i + 1,..., j - 1] balloons, then the maximum profit dp[i][j] = max(nums[i] * nums[k] * nums[j] + dp[i][k] + dp[k + 1][j]) , since dp[i][k] represents the maximum profit of bursting [i + 1, k - 1] balloons and dp[k + 1][j] represents the maximum profit of bursting [k,..., j - 1] balloons.

Code

C++

if(nums.size() == 0) return 0;
nums.insert(nums.begin(), 1);
nums.push_back(1);
int n = nums.size();
vector<vector<int>> dp(n, vector<int>(n, 0));
for(int l = 2; l < n; ++l)
{
    for(int i = 0; i < n - l; ++i)
    {
        int j = i + l;
        for(int k = i + 1; k < j; ++k)
            dp[i][j] = max(dp[i][j], dp[i][k] + dp[k][j] + nums[i] * nums[k] * nums[j]);
    }
}
return dp[0][n - 1];