我被挑戰以遞歸方式解決以下問題,但我仍然不能。用遞歸算法包裝一組盒子
問題:必須收拾所有項目從以下一組
int[] items = new int[] {4, 4, 2, 3};
到下面的框
int[] boxes = new int[] {5, 8};
目前,在算法結束時,我有
Item index: 2
Box index: 1
Items: 0, 0, 0, 3,
Boxes: 1, 2,
-------------------------------------------------
It is possible to distribute defined set of items in given boxes.
這是不正確的,因爲有一個項目3,有兩個盒子剩餘的ca pacity 1和2.我從「||」的右邊獲得的最終積極結果是,表達。
有人能指出錯誤的代碼或推薦正確的解決方案嗎?謝謝!
我的Java代碼如下:
public class Boxes
{
public static void main(String[] args)
{
int[] items = new int[] {4, 4, 2, 3};
int[] boxes = new int[] {5, 8};
System.out.println(String.format("It is %spossible to distribute defined set of items in given boxes.", IsFit(items, boxes, 0, 0) ? "" : "NOT "));
}
private static boolean IsFit(int[] items, int[] boxes, int boxIndex, int itemIndex)
{
if (boxIndex == boxes.length)
return false;
if (itemIndex == items.length)
return true;
boolean result =
IsFit(items, boxes, boxIndex + 1, itemIndex)
||
IsFit(items, boxes, boxIndex, itemIndex + 1)
;
if (result)
{
int storedValue = items[itemIndex];
if (boxes[boxIndex] >= storedValue)
{
boxes[boxIndex] -= storedValue;
items[itemIndex] = 0;
/*
System.out.println(String.format("Item index: %d", itemIndex));
System.out.println(String.format("Box index: %d", boxIndex));
System.out.print("Items: ");
for (int i : items)
System.out.print(String.format("%s, ", i));
System.out.println();
System.out.print("Boxes: ");
for (int b : boxes)
System.out.print(String.format("%s, ", b));
System.out.println();
System.out.println("-------------------------------------------------");
*/
result = IsFit(items, boxes, boxIndex, itemIndex + 1);
items[itemIndex] = storedValue;
boxes[boxIndex] += storedValue;
}
}
return result;
}
}
你能清楚地說明實際的挑戰是什麼? – matcheek 2013-03-15 14:17:25
是否意味着在箱子中分配物品,以便在運行結束時所有物品和箱子均爲0。還是意味着要說「不可能分發......」,因爲有物品和盒子空間仍然存在? – ghdalum 2013-03-15 14:20:21
判斷是否有可能將所有可用項目分散到給定的框中是必要的。 – 2013-03-15 14:24:36