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

    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] (33=9 points)
    ----> [1, 3, 3, 3, 1] (1
    1=1 points)
    ----> [1, 1] (33=9 points)
    ----> [] (2
    2=4 points)
    Note: The number of boxes n would not exceed 100.

    1.思考

    • 一开始想到的是DP,或者DFS搜索;
    • 下面的实现代码使用的DFS搜索;
    • 代码在本地运行时正确的,但是提交显示time limit exceeded,还要再优化;

    2.实现

    class Solution {
    public:
        //This algorithm is right, but time limit exceeded.
        int mp = 0;
    
    	int removeBoxes(vector<int>& boxes) {
    		if (boxes.empty())
    			return 0;
    		DFS(boxes, 0);
    		return mp;
    	}
    
    	void DFS(vector<int>& box, int point){
    		if (box.empty())
    			return;
    
    		int len = box.size();
    		int num = 0, color = box[0];
    		vector<int> b = box;
    		int i = 0, j = 0, p;
    
    		while (i<len){
    			b = box;
    			num = 0;
    			color = box[i];
    			j = i;
    			while (j<b.size()){
    				if (b[j] == color){
    					num++;
    					b.erase(b.begin() + j);
    					if (j < b.size())
    						continue;
    				}
    				else
    					break;
    			}
    			p = point + pow(num, 2);
    			DFS(b, p);
    			if (mp<p)
    				mp = p;
    			i += num;
    		}
    
    	}
        
    };
    
  • 相关阅读:
    虚拟机NetworkAdapter三种方式的区别
    skia
    android gralloc是什么意思
    两个工作机会
    Ubuntu apt-get更新源替换及加速方法
    Vuforia和Metaio相继被收购,开发者们还有这些AR引擎可以选
    OpenCV 为啥勾搭上 OpenGL
    感受2万元的黑科技 微软MR头显HoloLens测评
    影创 我们的职位
    java基础-servlet-2:生命周期
  • 原文地址:https://www.cnblogs.com/xuyy-isee/p/10864608.html
Copyright © 2011-2022 走看看