区间DP

  • 石子归并
    P1880. 石子合并 (每次合并两个,圆形操场)
    1000. Minimum Cost to Merge Stones (每次合并K个)
    312. Burst Balloons (tricky part is dp[i][j] 不包含端点)
  • 最优矩阵链乘
  • 最优三角形剖分
  • 最长回文子序列
    516. Longest Palindromic Subsequence
  • 回文子序列个数
  • 其他
    1246 和 1278 这两道题值得反复做
    1246. Palindrome Removal
    1278. Palindrome Partitioning III

P1880. 石子合并

  • 为什么两倍的数组可以模拟环?
  • 和House Robber II 的环有何不同?
    House Robber II 是首尾不能同时取,所以忽略首和忽略尾做两次线性DP即可
import java.util.Arrays;
import java.util.Scanner;

public class LuoP1880 {
    public static void main(String[] args) {
        //读数据
        Scanner in  = new Scanner(System.in);
        int n = in.nextInt();
        int[] nums = new int[2*n];      //两倍长度的array模拟环
        for (int i = 0; i < n; i++) nums[i] = nums[i+n] = in.nextInt();
        in.close();
        //前缀和 以及 两个 DP数组
        int N = 2 * n;
        int[] preSum = new int[2*N+1];
        for (int i = 0; i < N; i++) preSum[i+1] = preSum[i] + nums[i];
        int[][] dp1 = new int[N][N];
        int[][] dp2 = new int[N][N];
        for (int[] temp : dp1) Arrays.fill(temp, Integer.MAX_VALUE);
        for (int i = 0; i < N; i++) dp1[i][i] = 0;
        //区间DP,状态转移
        for (int l = 2; l <= n; l++) {
            for (int i = 0; i <= N-l; i++) {
                int j = i + l - 1;
                if (j >= N) continue;
                for (int k = i; k < j; k++) {
                    dp1[i][j] = Math.min(dp1[i][j], dp1[i][k] + dp1[k+1][j] + preSum[j+1] - preSum[i]);
                    dp2[i][j] = Math.max(dp2[i][j], dp2[i][k] + dp2[k+1][j] + preSum[j+1] - preSum[i]);
                }
            }
        }
        int maxRes = Integer.MIN_VALUE;
        int minRes = Integer.MAX_VALUE;
        for (int i = 0; i < n; i++) {
            maxRes = Math.max(maxRes, dp2[i][i+n-1]);
            minRes = Math.min(minRes, dp1[i][i+n-1]);
        }
        System.out.println(minRes);
        System.out.println(maxRes);
    }
}

1000. Minimum Cost to Merge Stones

//bottom-up DP
//time complexity: O(n^3/K), space complexity: O(n^2)
//because in the inner-most loop, i can skip a lot of invalid cases
class Solution {
    public int mergeStones(int[] stones, int K) {
        int n = stones.length;
        if ((n-1) % (K-1) != 0) return -1;
        //dp[i][j] is the min cost to merge [i, j] to 1 pile 
        int[] preSum = new int[n+1];
        for (int i = 0; i < n; i++) preSum[i+1] = preSum[i] + stones[i];
        int[][] dp = new int[n][n];
        for (int[] temp : dp) Arrays.fill(temp, Integer.MAX_VALUE);
        for (int i = 0; i < n; i++) dp[i][i] = 0;
        
        for (int l = 2; l <= n; l++) {
            for (int i = 0; i <= n-l; i++) {
                int j = i+l-1;
                //分成两部分[i, m], [m+1, j]
                //dp[i][j] = min(dp[i][j], dp[i][m] + dp[m+1][j])
                //如何可以知道m是一个valid split? [i, m] can form one pile 
                for (int m = i; m < j; m += K-1) {
                    dp[i][j] = Math.min(dp[i][j], dp[i][m] + dp[m+1][j]); 
                }
                if ((l-1) % (K-1) == 0) {
                    dp[i][j] += preSum[j+1] - preSum[i];
                }
            }
        }
        return dp[0][n-1];
    }
}
//DFS with memorization, top-down dynamic programming
class Solution {
    public int mergeStones(int[] stones, int K) {
        int n = stones.length;
        //n-1个能merge成K-1个pile,so that it kan form K in the last Merge
        if ((n-1) % (K-1) != 0) return -1;
        int[] preSum = new int[n+1];
        //求前缀和, merge的时候cost + the sum of an K-length interval, O(1)
        for (int i = 0; i < n; i++) preSum[i+1] = preSum[i] + stones[i];
        //if memo[i][j] is Max, this range is not processed before
        int[][] memo = new int[n][n];
        for (int[] temp : memo) Arrays.fill(temp, Integer.MAX_VALUE);
        //[0, n-1] can form a valid pile
        return dfs(memo, 0, n-1, K, preSum);
    }
    private int dfs(int[][] memo, int i, int j, int K, int[] preSum) {
        int len = j - i + 1;
        if (len < K) {
            return 0;
        }
        if (memo[i][j] != Integer.MAX_VALUE) {
            return memo[i][j];
        }
        int cost = Integer.MAX_VALUE;
        for (int m = i; m < j; m += K-1) {
            //[i, i] = 1, [i, i+K-1] = 1, [i, i+K-1+K-1] = 2 valid piles
            //assume [i, m] forms 2 valid piles, [m+1, j] forms K-2 piles
            //        |                              |
            //   cost < MAX                      cost should be zero  
            //Mewrge the 2 piles and K-2 piles after the for loop (after find the minimum cost split)
            cost = Math.min(cost, dfs(memo, i, m, K, preSum) + dfs(memo, m+1, j, K, preSum));
        }
        //合并
        //No mather where we split it, the merge cost in this level is the sum(i, j) 
        if ((len-1) % (K-1) == 0) {
            cost += preSum[j+1] - preSum[i];
        }
        return memo[i][j] = cost;
    }
}

312. Burst Balloons

  • 有趣的点
    dp[i][j] 的表示:burst all balloons in(i, j)i, j not included
    spliter 的选取:k 和 i, j 绝对不重叠 k = i+1; k < j; k++
class Solution {
    public int maxCoins(int[] preNums) {
        int n = preNums.length + 2;
        int[] nums = new int[n];
        for (int i = 1; i < n-1; i++) {
            nums[i] = preNums[i-1];
        }
        nums[0] = nums[n-1] = 1;
        
        //dp[i][j] is the max cois if I burst all (i, j) ballons 
        //NOTE: not include i and j, so that i and j can be added
        int[][] dp = new int[n][n];
        for (int l = 2; l < n; l++) {
            //i 和 j是interval的两端,k才是中间的那个      
            for (int i = 0; i < n-l; i++) {
                int j = i + l;
                for (int k = i+1; k < j; k++) {
                    //base case is: i,j,k are adjacent
                    dp[i][j] = Math.max(dp[i][j], dp[i][k] + dp[k][j] + nums[i] * nums[k] * nums[j]);
                }
            }
        }
        return dp[0][n-1];
    }
}
class Solution {
    public int maxCoins(int[] preNums) {
        int n = preNums.length + 2;
        int[] nums = new int[n];
        for (int i = 1; i < n-1; i++) {
            nums[i] = preNums[i-1];
        }
        nums[0] = nums[n-1] = 1;
        int[][] memo = new int[n][n];
        return burst(memo, 0, n-1, nums);
    }
    private int burst(int[][] memo, int i, int j, int[] nums) {
        if (memo[i][j] != 0) return memo[i][j];
        int coins = 0;
        for (int k = i+1; k < j; k++) {
            // coins = Math.max(coins, dp[i][k] + dp[k][j] + nums[i] * nums[k] * nums[j]);
            coins = Math.max(coins, burst(memo, i, k, nums) + burst(memo, k, j, nums) + nums[i] * nums[k] * nums[j]);
        }
        return memo[i][j] = coins;
    }
}

516. Longest Palindromic Subsequence

//top-down
class Solution {
    public int longestPalindromeSubseq(String s) {
        int n = s.length();
        int[][] memo = new int[n][n];
        return lps(memo, 0, n-1, s);
    }
    private int lps(int[][] memo, int i, int j, String s) {
        if (i == j) return 1;
        if (i > j) return 0;
        if (memo[i][j] != 0) return memo[i][j];
        if (s.charAt(i) == s.charAt(j)) {
            return memo[i][j] = lps(memo, i+1, j-1, s) + 2;
        } else {
            return memo[i][j] = Math.max(lps(memo, i+1, j, s), lps(memo, i, j-1, s));
        }
    }
}

//bottom-up
class Solution {
    //dp[i][j] is the longest subsequence in [i, j]
    //if s.charAt(i) == s.charAt(j) dp[i][j] = dp[i+1][j-1] + 2
    //else dp[i][j] = Math.min(dp[i+1][j], dp[i][j-1])
    //for every state transition, we need the information of next row and last column
    public int longestPalindromeSubseq(String s) {
        int n = s.length();
        int[][] dp = new int[n][n];
        for (int i = n-1; i >= 0; i--) {
            dp[i][i] = 1;
            for (int j = i+1; j < n; j++) {
                if (s.charAt(i) == s.charAt(j)) {
                    dp[i][j] = dp[i+1][j-1] + 2;
                } else {
                    dp[i][j] = Math.max(dp[i+1][j], dp[i][j-1]);
                }
            }
        }
        return dp[0][n-1];
    }
}

你可能感兴趣的:(区间DP)