zoukankan      html  css  js  c++  java
  • 546. Remove Boxes

    Given several boxes with different colors represented by different positive numbers. 
    You may experience several rounds to remove boxes until there is no box left. Each time you can choose some continuous boxes with the same color (composed of k boxes, k >= 1), remove them and get k*k points.
    Find the maximum points you can get.

    Example 1:
    Input:

    [1, 3, 2, 2, 2, 3, 4, 3, 1]
    

    Output:

    23
    

    Explanation:

    [1, 3, 2, 2, 2, 3, 4, 3, 1] 
    ----> [1, 3, 3, 4, 3, 1] (3*3=9 points) 
    ----> [1, 3, 3, 3, 1] (1*1=1 points) 
    ----> [1, 1] (3*3=9 points) 
    ----> [] (2*2=4 points)

    Approach #1: three dimensional DP. [C++] [Hard]

    class Solution {
    public:
        int removeBoxes(vector<int>& boxes) {
            int n = boxes.size();
            m_ = vector<vector<vector<int>>>(n, vector<vector<int>>(n, vector<int>(n, 0)));
            return dfs(boxes, 0, n-1, 0);
        }
        
    private:
        vector<vector<vector<int>>> m_;
        
        int dfs(const vector<int>& boxes, int l, int r, int k) {
            if (l > r) return 0;
            if (m_[l][r][k] != 0) return m_[l][r][k];
            while (l < r && boxes[r-1] == boxes[r]) {--r; ++k;}
            m_[l][r][k] = dfs(boxes, l, r-1, 0) + (k + 1) * (k + 1);
            for (int i = l; i < r; ++i) {
                if (boxes[i] == boxes[r])
                    m_[l][r][k] = max(m_[l][r][k], dfs(boxes, l, i, k + 1) + dfs(boxes, i + 1, r - 1, 0));
            }
            return m_[l][r][k];
        }
    };
    

      

    Analysis:

    dp[i][j][k] = max score of subarray b[i] ~ b[j] if there are k boxes that have the same color as b[j] following b[j]. Those k boxes are from box[j+1] ~ box[n], to simulate boxes with other colors are removed first.

    Transition:

    dp[i][j][k] = dp[i][j-1][0] + (k + 1)^2    # case 1

           dp[i][p][k+1] + dp[p+1][j-1][0]  # case 2

    Case 1: drop box[j], remove k + 1 boxes.

    Case 2: Try all breakpoints p, attach a[j] to a[p], i <= p < j, box[p] == box[j].

    Ans:

    dp[0][n-1][0]

    Tim complexity: O(n^4) Space complexity: O(n^3)

    Reference:

    https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-546-remove-boxes/

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    客户端IP获取
    文件下载公共方法 以及调用
    文件压缩和解压缩工具类
    下载
    URLencoder类防止下载后的文件名乱码
    SQL行转列
    处理千万级以上的数据提高查询速度的方法
    获取本月的第一天和最后一天
    【机器学习理论】概率论与数理统计--假设检验,卡方检验,t检验,F检验,方差分析
    【机器学习实践】Jupyter Notebook安装 侧边导航栏功能 操作及其他常用扩展功能介绍
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10492800.html
Copyright © 2011-2022 走看看