1. 程式人生 > >Leetcode312. Burst Balloons (DP+DFS)

Leetcode312. Burst Balloons (DP+DFS)

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:

  • 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:

Input: [3,1,5,8]
Output: 167 
Explanation: 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個位置消去,遞迴之後的結果是arr[l-1]*arr[i]*arr[r+1]
dp[l][r] = max(dp[l][r], dp[l][i-1]+dp[i+1][j]+arr[l-1]*arr[r+1]*arr[i]

class Solution {
    int dp[505][505];
    int n;
    vector<int> arr;
    int dfs(int l, int r) {
        if(l>r) return 0;
        if(dp[l][r] > 0)
            return dp[
l][r]; for(int i=l;i<=r;i++) { int left = l-1<0?1:arr[l-1]; int right = r+1>=n?1:arr[r+1]; dp[l][r] = max(dp[l][r], dfs(l, i-1) + dfs(i+1, r) + arr[i]*left*right); } return dp[l][r]; } public: int maxCoins(vector<int>& nums) { arr = nums; n = nums.size(); return dfs(0, n-1); } };