9.10 give you a bunch of n boxes, Box W, H, D. The box cannot be flipped, and when the box is piled up, the width, height and depth of the box below must be greater than the box above. Implement a method to build the highest pile of boxes, the height of the box heap is the sum of the height of each box.
Solution:
To solve this problem, we need to find the relationship between different sub-problems.
Let's say we have the following boxes: B1, B2,..., bn. The height of the maximum box heap that can be piled is equal to max (the highest box heap at the bottom of the B1, the bottom is the highest box heap of B2, the bottom is the highest box heap of bn). In other words, just try to use each box as the bottom of the box pile and set the highest possible height, you can find the highest height of the box pair.
How to implement backtracking:
#include <iostream>#include<vector>using namespacestd;structbox{intheight; intwide; intdepth; Box (intHintWintd): Height (h), wide (w), depth (d) {}};BOOLIsValid (Vector<box> &Path,box B) { if(Path.empty ())return true; Box Top=path[path.size ()-1]; returnb.depth<top.depth&&b.height<top.height&&b.wide<top.wide;}voidHelper (vector<box> &boxes,vector<box> &path,int&maxheight) { inti; for(i=0; I<boxes.size (); i++) { if(IsValid (Path,boxes[i])) {path.push_back (boxes[i]); Helper (boxes,path,maxheight); Path.pop_back (); } } if(i==boxes.size ()) { intj,sum=0; for(j=0; J<path.size (); J + +) {sum+=Path[j].height; } if(sum>maxheight) MaxHeight=sum; return; }}intMaxboxtower (Vector<box> &boxes) {Vector<box>path; intmaxheight=0; Helper (boxes,path,maxheight); returnMaxHeight;}intmain () {vector<box> b= {box (2,2,2), Box (1,2,1), Box (3,2,1), Box (3,3,3)}; cout<<maxboxtower (b) <<Endl;}
careercup-recursive and dynamic programming 9.10