原题链接在这里:https://leetcode.com/problems/minimum-cost-to-merge-stones/
题目:
There are N
piles of stones arranged in a row. The i
-th pile has stones[i]
stones.
A move consists of merging exactly K
consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these K
piles.
Find the minimum cost to merge all piles of stones into one pile. If it is impossible, return -1
.
Example 1:
Input: stones = [3,2,4,1], K = 2 Output: 20 Explanation: We start with [3, 2, 4, 1]. We merge [3, 2] for a cost of 5, and we are left with [5, 4, 1]. We merge [4, 1] for a cost of 5, and we are left with [5, 5]. We merge [5, 5] for a cost of 10, and we are left with [10]. The total cost was 20, and this is the minimum possible.
Example 2:
Input: stones = [3,2,4,1], K = 3 Output: -1 Explanation: After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.
Example 3:
Input: stones = [3,5,1,2,6], K = 3 Output: 25 Explanation: We start with [3, 5, 1, 2, 6]. We merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6]. We merge [3, 8, 6] for a cost of 17, and we are left with [17]. The total cost was 25, and this is the minimum possible.
Note:
1 <= stones.length <= 30
2 <= K <= 30
1 <= stones[i] <= 100
题解:
Each merge step, piles number decreased by K-1. Eventually there is only 1 pile. n - mergeTimes * (K-1) == 1. megeTimes = (n-1)/(K-1). If it is not divisable, then it could not merge into one pile, thus return -1.
Let dp[i][j] denotes minimum cost to merge [i, j] inclusively.
m = i, i+1, ... j-1. Let i to m be one pile, and m+1 to j to certain piles. dp[i][j] = min(dp[i][m] + dp[m+1][j]).
In order to make i to m as one pile, [i,m] inclusive length is multiple of K. m moves K-1 each step.
If [i, j] is multiple of K, then dp[i][j] could be merged into one pile. dp[i][j] += preSum[j+1] - preSum[i].
return dp[0][n-1], minimum cost to merge [0, n-1] inclusively.
Time Complexity: O(n^3/K).
Space: O(n^2).
AC Java:
1 class Solution { 2 public int mergeStones(int[] stones, int K) { 3 int n = stones.length; 4 if((n-1)%(K-1) != 0){ 5 return -1; 6 } 7 8 int [] preSum = new int[n+1]; 9 for(int i = 1; i<=n; i++){ 10 preSum[i] = preSum[i-1] + stones[i-1]; 11 } 12 13 int [][] dp = new int[n][n]; 14 for(int size = 2; size<=n; size++){ 15 for(int i = 0; i<=n-size; i++){ 16 int j = i+size-1; 17 dp[i][j] = Integer.MAX_VALUE; 18 19 for(int m = i; m<j; m += K-1){ 20 dp[i][j] = Math.min(dp[i][j], dp[i][m]+dp[m+1][j]); 21 } 22 23 if((size-1) % (K-1) == 0){ 24 dp[i][j] += preSum[j+1] - preSum[i]; 25 } 26 } 27 } 28 29 return dp[0][n-1]; 30 } 31 }