168. Burst Balloons

168. Burst Balloons

Tag:

Dynamic Problem

Main Idea:

DP-range Problem
Before dive into the DP problem, we will process the vector first. What we are going to do to insert at both the front and the end a 1. In this way, the <nums> will be “1 <nums> 1”, and the length will increase 2.

  1. State:

    • dp[i][j] : the maximum coin can collect between (i, j) after bursting the balloons from i+1 to j-1.
  2. Update Function:

    • For all the k that i< k< j, dp[i][j] = max(dp[i][j], dp[i][k] + dp[k][j] + nums[i] * nums[k] * nums[j]) .
    • note here, it’s not to compare nums[i] * nums[k] * nums[j] , but dp[i][k] + dp[k][j] + nums[i] * nums[k] * nums[j] . Because the former one only calculate the one step while dp[i][j] is more than just one step. In this sense, don’t forget to plus dp[i][k] + dp[k][j] .
  3. Initialization:

    • As mentioned above, process the nums before dive into DP.
    • For-loop of i should from the end to the begin(thats n-1 ===> 0).
  4. Answer:
    dp[0][len-1]

Tips/Notes:

  1. In code part, here is one thing need to pay attention. Our goal it to iterate the k that i < k < j. Instead of iterate i by 0 -> n-1, it should be n-1 -> 0. If we implement by the former one, then dp[0][len-1] will be update at very beginning, which is not our goal. Thus, as we implement by the latter one, it means we dp[0][j] is the very last part to update. It reflect the the main idea of Dynamic Proeblm (solving larger problem by solving smaller problem).

Time/Space Cost:

Time Cost:   O ( n 3 ) \ O(n^3)
Space Cost:   O ( n 2 ) \ O(n^2)

Code:

class Solution {
public:
    /**
     * @param nums: A list of integer
     * @return: An integer, maximum coins
     */
    
    vector<int> process(vector<int> &nums){
        int len = nums.size();
        vector<int> tmp(len+2);
        tmp.push_back(1);
        for(int i = 0; i < len; i++){
            tmp.push_back(nums[i]);
        }
        tmp.push_back(1);
        return tmp;
        
    }
    
    
    int maxCoins(vector<int> &nums) {
        // write your code here
        if(nums.empty())
            return 0;
        nums = process(nums);
        int len = nums.size();
        vector<vector<int>> dp(len, vector<int>(len, 0));
        
        // As mentioned at Tips, it for-loop of i should from end to begin.
        for (int i = nums.size() - 1; i >= 0; i--){
            for(int j = i + 2; j < len; j++){
                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][len-1];
    }
};

发布了10 篇原创文章 · 获赞 0 · 访问量 99

猜你喜欢

转载自blog.csdn.net/Zahb44856/article/details/103933021