【发布时间】:2018-06-26 12:44:48
【问题描述】:
升降机的容量通常是有限的,无论是空间(人)还是负载(公斤)。想象我们有 小型升降机,最多可搭载 6 人,最大负载为 500公斤。假设有 13 个人在等待,其权重如下:10、30、40、41、80、90、50、55、 92、66、82、62 和 70 公斤。编写一个递归程序,找到一群不知道的人 超过最大容量,但具有以 kg 为单位的最大可能负载。 (提示:有一个有效的 超过 470kg 的溶液)
public static void main (String[] Args)
{
ArrayList<Integer> s = new ArrayList<Integer>(); //List of unexplored
int[] weight0 = { 10, 30, 40, 41, 80, 90, 50, 55, 92, 66, 82, 62,70}; //Initial state
int target = 500; //Goal state
System.out.println(liftGroup(weight0,0,target, s) + " way(s)"); //Recursive function
}
static int liftGroup (int[] weight,int c,int target, ArrayList<Integer> s){
assert weight != null : "array should be initialized";
assert c >= 0 && c <= weight.length;
assert s != null : "ArrayList should be initialized";
int sumOfUntried = 0;
if (c > 6) {
showSoulution(s);
return 1;
}
else if (target < 0) {
return 0;
}
else if (c >= weight.length) { //that's okay?
return 0;
}
int min = weight[c];
for (int i = c; i < weight.length; i++) {
sumOfUntried += weight[i];
if(weight[i]<min)
min=weight[i];
}
if(min>target) // If you find one BIG fatty
{
return 0;
}
if (sumOfUntried > target) { //Correct
return 0;
}
else {
s.add(weight[c]);
int with = liftGroup(weight, c + 1, target - weight[c], s);
s.remove(s.size() - 1);
int without = liftGroup(weight, c + 1, target, s);
return with + without;
}
}
/*
* Prints the ArrayList with the solution
*/
private static void showSoulution(ArrayList<Integer> s)
{
assert s != null : "ArrayList should be initialized";
System.out.println("Solution: " + s);
}}
我的问题是理解和使用基本情况:
- 当人数不超过最大限制时。你有一个解决方案。
- 但是我该如何遵守这两个目标呢?
【问题讨论】: