LeetCode 1000. Minimum Cost to Merge Stones (interval DP)

According to the cold god question  https://leetcode.com/problems/minimum-cost-to-merge-stones/discuss/247567/JavaC%2B%2BPython-DP

Topic:

Each time you can combine consecutive K piles of stones into one pile. The cost is the sum of K piles. Ask the minimum cost to combine all stones into 1 pile. If this is not possible, -1 is returned.

answer:

Because, every time the K reactor becomes a reactor, that is to say each time K-1 minus the heap, the last remaining heap, so only in   (the n-- 1 )% (K - 1 ) == 0   can Synthesize 1 pile.

 

 dp [i] [j]  represents     the minimum cost of stones [i..j] after merging as much as possible.

 

Then enumerate the i-th stone and the first few stones to form a pile. Only when the length is   1 + (K- 1 ) * x   can a pile be combined, so the enumeration length is increased by   K- 1  .

 

class Solution {
public:
    int mergeStones(vector<int>& stones, int K) {
        int n = stones.size();
        if ((n-1) % (K-1)) return -1;
        vector<int> prefix(n + 1);
        for (int i = 1; i <= n; i++) prefix[i] = prefix[i-1] + stones[i - 1];
        vector<vector<int>> dp(n, vector<int > (n, 0 ));
         // When ji <K does not need to be merged so the value is 0 
        for ( int l = K- 1 ; l <n; l ++ ) {
             for ( int s = 0 ; s + l < n; s ++ ) {
                 int e = s + l; 
                dp [s] [e] = INT_MAX;
                 for ( int m = s; m <e; m + = K- 1 ) { 
                    dp [s] [e] = min (dp [s] [e], dp [s] [m] + dp [m + 1 ] [e]); 
                } 
                //l% (K-1) == 0 It just happens to be able to synthesize a bunch
                 // because the enumeration is a left synthesizing bunch, so after left and right addition must be greater than a bunch, it is not the simplest state
                 // so you need to merge and merge again. The value is the interval and 
                if (l% (K- 1 ) == 0 ) { 
                    dp [s] [e] + = prefix [e + 1 ] -prefix [s]; 
                } 
            } 
        } 
        return dp [ 0 ] [n- 1 ]; 
    } 
};

 

Guess you like

Origin www.cnblogs.com/wenruo/p/12717004.html