package demo4;public class Zuiyouzhuangzai { static int[] boxes = {4, 10, 7, 11, 3, 5, 14, 2}; static int max = 0; static int cur = 0; public static void main(String[] args) { load(0, 0); System.out.println("最多能装入的集装箱数量为:"+max); } public static void load(int count, int weight) { if (weight > 30) { return; } if (count == 8) { max = Math.max(max, count); return; } for (int i = 0; i < 8; i++) { if (boxes[i] != 0) { int temp = boxes[i]; boxes[i] = 0; load(count + 1, weight + temp); boxes[i] = temp; } } }}这个代码有非常严重的问题,无法得出准确结果5,请马上修改并说明原因
时间: 2024-02-14 21:10:40 浏览: 10
这段代码存在两个问题:
1. 在load方法中,当count == 8时,虽然会比较当前的count和max,但是没有考虑到weight是否合法,即weight可能大于30,导致结果不准确。
2. 在load方法中,循环遍历8个集装箱时,没有考虑到集装箱的重量可能为0,即没有装任何物品,导致结果不准确。
修改后的代码如下:
```
package demo4;
public class Zuiyouzhuangzai {
static int[] boxes = {4, 10, 7, 11, 3, 5, 14, 2};
static int max = 0;
static int cur = 0;
public static void main(String[] args) {
load(0, 0);
System.out.println("最多能装入的集装箱数量为:" + max);
}
public static void load(int count, int weight) {
if (weight > 30 || count == 8) {
max = Math.max(max, count);
return;
}
for (int i = 0; i < 8; i++) {
if (boxes[i] > 0) {
int temp = boxes[i];
boxes[i] = 0;
load(count + 1, weight + temp);
boxes[i] = temp;
}
}
}
}
```
修改后的代码中,当weight大于30或者count等于8时,直接比较count和max,同时return,避免了weight大于30时结果不准确的问题;同时在循环遍历8个集装箱时,只有集装箱的重量大于0时才会进行装载,避免了集装箱重量为0时导致结果不准确的问题。