leetcode(546)消消乐(动态规划)

题目:给你一组方块:每一种数字都代表一种颜色,你该采取怎样的消去策略,能确保自己的得分最高呢?(我们假设每次消去n个方块,就可以得到n的平方这么多的分数)
例:
输入:1,3,2,2,2,3,4,3,1
输出:23
(1)消去相连的3个2,得到3* 3=9分,剩余 1,3,3,4,3,1
(2)消去4,得到1*1 =1分,剩余1,3,3,3,1
(3)消去相连的3个2,得到3 * 3=9分,剩余1,1
(4)消去最后2个1,得到2 *2=4分
(5)最后得出:最高的分为9+9+1+4=23分。

方块少的时候,我们还可以通过贪心算法“猜”出结果,但是方块一多,就没那么简单了,解决这个问题,我们可以采用动态规划的方法——假设方块数组s[k],假设动态方程f[i][j][m](i表示s[i],j表示s[j],m表示s[j]之后的元素中,与s[j]相同的元素的个数,m可以取零到个数最多之间的所有数),我们的最终目的是要求出f[0][s.length][0]的值。
动态规划的方程:
在这里插入图片描述

 class Solution {
    
    
        public int removeBoxes(int[] boxes) 

            int length=boxes.length;
            int [][][]dp=new int[length][length][length];
            return recursion(boxes,dp,0,length-1,0);
        }
        private int recursion(int[]boxes,int[][][]dp,int start,int end,int theSame){
    
    
            if(end<start)
                return 0;
            if(dp[start][end][theSame]!=0)
                return dp[start][end][theSame];
            while(end>0&&boxes[end]==boxes[end-1]){
    
    
                end--;
                theSame++;
            }
            dp[start][end][theSame]=recursion(boxes,dp,start,end-1,0)+(theSame+1)*(theSame+1);
            for(int i=start;i<end;i++){
    
    
                if(boxes[i]==boxes[end]){
    
    
                    dp[start][end][theSame]=Math.max(dp[start][end][theSame],recursion(boxes,dp,start,i,theSame+1)+
                            recursion(boxes,dp,i+1,end,0));
                }
            }
            return dp[start][end][theSame];
        }
    }

猜你喜欢

转载自blog.csdn.net/CY2333333/article/details/108022676