class Solution { public int getLengthOfOptimalCompression(String s, int k) { int n = s.length(); int[][] dp = new int[n+1][k+1]; // dp[i][j]:考虑前i个字符最多删除j个的最小长度 for(int[] d : dp) Arrays.fill(d,Integer.MAX_VALUE >> 1); dp[0][0] = 0; for(int i = 1; i <= n; i++) { for(int j = 0; j <= k && j <= i; j++) { if(j > 0) dp[i][j] = dp[i-1][j-1]; // 情况1:删除第i个字符 // 情况2:保留第i个字符 int same = 0, diff = 0; for(int f = i; f >= 1 && diff <= j; f--) { // 向前遍历与第i个字符相同的字符则考虑保留 if(s.charAt(f-1) == s.charAt(i-1)) { dp[i][j] = Math.min(dp[i][j],dp[f-1][j-diff] + calc(++same)); } else { diff++; } } } } return dp[n][k]; } public int calc(int n) { if(n == 1) return 1; if(n < 10) return 2; if(n < 100) return 3; return 4; } }