LintCode_168 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.
- You may imagine nums[-1] = nums[n] = 1. They are not real therefore you can not burst them.
- 0 ≤ n ≤ 500, 0 ≤ nums[i] ≤ 100

Example

Given [4, 1, 5, 10]
Return 270

nums = [4, 1, 5, 10] burst 1, get coins 4 * 1 * 5 = 20
nums = [4, 5, 10]    burst 5, get coins 4 * 5 * 10 = 200 
nums = [4, 10]       burst 4, get coins 1 * 4 * 10 = 40
nums = [10]          burst 10, get coins 1 * 10 * 1 = 10

Total coins 20 + 200 + 40 + 10 = 270

思路是使用dp, dp[l][r] 是刺破l至r(不包括l和r)所以只要确定中间最后一个刺破的就行了,别忘了在原始数据头尾都加1;


class Solution {
public:
    /**
     * @param nums a list of integer
     * @return an integer, maximum coins
     */  
    int maxCoins(vector& nums) {
        // Write your code here
        nums.push_back(1);
        nums.insert(nums.begin(), 1);
        const int len = (int)nums.size();
        int dp[len][len];
        memset(dp, 0, sizeof(dp));
        for (int k = 2; k < len; k++) {
            for (int l = 0; l + k < len; l++) {
                int r = l + k;
                for (int mid = l + 1; mid < r; mid++) {
                    dp[l][r] = max(dp[l][r], 
                                   dp[l][mid] + dp[mid][r] + nums[l] * nums[mid] * nums[r]);
                }
            }
        }
        return dp[0][len - 1];
    }
};




你可能感兴趣的:(LintCode)