Programmer Interview Gold Code-Interview Question 08.13. Stacking Boxes (DP)

1. Title

Stack of boxes. Give you a pile of n boxes, the box is wide wi, deep di, high hi.
The boxes cannot be turned over. When stacking the boxes, the width, height and depth of the lower box must be greater than the upper box.
Implement a method to build the tallest pile of boxes. The height of the box stack is the sum of the height of each box .

输入使用数组[wi, di, hi]表示每个箱子。

示例1:
 输入:box = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
 输出:6
 
示例2:
 输入:box = [[1, 1, 1], [2, 3, 4], [2, 6, 7], [3, 4, 5]]
 输出:10
 
提示:
箱子的数目不大于3000个。

Source: LeetCode (LeetCode)
Link: https://leetcode-cn.com/problems/pile-box-lcci The
copyright belongs to the deduction network. Please contact the official authorization for commercial reprint, and please indicate the source for non-commercial reprint.

2. Problem solving

class Solution {
public:
    int pileBox(vector<vector<int>>& box) {
    	sort(box.begin(), box.end(),[&](auto a, auto b) {
    		return a[0] > b[0];//宽降序
    	});
    	int i, j, n = box.size();
    	vector<int> dp(n,0);//以i箱子为顶的最大高度
    	for(i = 0; i < n; ++i)
    	{
    		dp[i] = box[i][2];//初始化自身高度
    		for(j = 0; j < i; ++j)//跟前面的比较
    		{
    			if(box[i][0] < box[j][0] && box[i][1] < box[j][1]
    					&& box[i][2] < box[j][2])//满足条件
    			{
    				dp[i] = max(dp[i], box[i][2]+dp[j]);//可以叠加,取最大的
    			}
    		}
    	}
    	return *max_element(dp.begin(),dp.end());
    }
};

280 ms 16.7 MB

Published 849 original articles · 2256 thumbs up · 440,000 visits +

Guess you like

Origin blog.csdn.net/qq_21201267/article/details/105538496