【发布时间】:2012-09-24 00:34:53
【问题描述】:
你有一堆 n 个盒子,宽度为 wi,高度为 hi,深度为 迪。盒子不能旋转,只能堆叠在一个上面 另一个如果堆栈中的每个盒子都大于或等于上面的盒子 它的宽度、高度和深度。实现一个方法来构建 可能的最高堆栈,其中堆栈的高度是 每个盒子的高度。
我知道有几篇文章可以讨论使用动态编程来解决它。由于我想练习编写递归代码,所以我写了以下代码:
const int not_possible = 999999;
class box{
public:
int width;
int depth;
int height;
box(int h=not_possible, int d=not_possible, int w=not_possible):
width(w), depth(d), height(h) {}
};
bool check_legal(box lower, box upper){
return (upper.depth<lower.depth) &&
(upper.height<lower.height) &&
(upper.width<lower.width);
}
void highest_stack(const vector<box>& boxes, bool* used, box cur_level, int num_boxes, int height, int& max_height)
{
if(boxes.empty())
return;
bool no_suitable = true;
for(int i = 0; i < num_boxes; ++i){
box cur;
if(!(*(used+i)) && check_legal(cur_level, boxes[i])){
no_suitable = false;
cur = boxes[i];
*(used+i) = true;
highest_stack(boxes, used, cur, num_boxes, height+cur.height, max_height);
*(used+i) = false;
no_suitable = true;
}
}
if(no_suitable){
cout << height << endl; //for debug
if(height > max_height)
max_height = height;
return;
}
}
我已经使用大量示例对其进行了测试。例如:
boxes.push_back(box(4,12,32));
boxes.push_back(box(1,2,3));
boxes.push_back(box(2,5,6));
highest_stack(boxes, used, cur, boxes.size(), 0, max_height);
在函数highest_stack中,有一行cout << height << endl;用于输出。如果我评论no_suitable = true;
输出是:1 2 4; 1 2; 1, 1 4;
如果我不评论no_suitable = true;
输出是:1 2 4; 2 4; 4; 1 2; 2; 1个; 1 4; 0
它们都可以给出正确的结果,即 7。
My question is: (1) Can anyone help me verify my solution? (2) Is there any more elegant recursive code for this problem?我不认为我的代码很优雅。 谢谢
【问题讨论】:
标签: algorithm recursion dynamic-programming