我一直在研究過去幾天似乎按預期工作的內容,但是我正在尋找改進方法。我有一組n個項目,我需要放在一起,這些項目組必須滿足所有的下列要求:最優化的方式來組合n個大小爲k的特殊組,以滿足特定要求
- 2項從類別從類別B A
- 2項
- 2從C類物品從類別d
- 2個項目
- 1從E類項我目前使用以下遞歸方法把米
y組合在一起並且isValid()方法用於確定組是否符合標準。
void getGroups(String[] arr, int len, int startPosition, String[] result) {
if(len == 0) {
Group group = new Group(Arrays.asList(result));
if(group.isValid()) {
validGroups.add(group);
group.printGroup();
}
return;
}
for(int i = startPosition; i <= arr.length - len; i++) {
result[result.length - len] = arr[i];
getGroups(arr, len - 1, i + 1, result);
}
}
我能看到有效的結果幫我印在程序運行時,但是,我有工作可以超過100項項目的原始大小。這意味着將有大量的可能的組遍歷並且很多次程序從未實際完成。
我知道現在有一堆浪費的迭代,例如,如果在某個時候我檢測到一個組是無效的,因爲它有3個來自類別A的項目,我應該可以繼續前進。我不確定我現在的方法是否是最好的方法,或者如果我應該先將這些項目分成它們各自的組,然後再將它們只組合在一起。任何幫助,將不勝感激。謝謝。
編輯:我試圖讓該方法比我的實際方法更簡單一些。我的實際方法需要創建一個包含它們的值及其類別的對象數組。我想對於這個例子,我們可以假定每個類別都由它包含的字符串列表來表示。該方法可以這樣調用:
String[] items = {"test1", "test2", "test3", "test4", "test5", "test6", "test7",
"test8", "test9", "test10", "test11", "test12", "test13",
"test14", "test15", "test16", "test17", "test18"};
getGroups(items, 9, 0, new String[9]);
EDIT2:
List<String> catA = new ArrayList<String>();
catA.add("test1");
catA.add("test2");
catA.add("test3");
catA.add("test4");
List<String> catB = new ArrayList<String>();
catB.add("test5");
catB.add("test6");
catB.add("test7");
catB.add("test8");
List<String> catC = new ArrayList<String>();
catC.add("test9");
catC.add("test10");
catC.add("test11");
catC.add("test12");
List<String> catS = new ArrayList<String>();
catD.add("test13");
catD.add("test14");
catD.add("test15");
catD.add("test16");
List<String> catE = new ArrayList<String>();
catE.add("test17");
catE.add("test18");
輸出:
{"test1", "test2", "test5", "test6", "test9", "test10", "test13", "test14", "test17"} {"test1", "test2", "test5", "test6", "test9", "test10", "test13", "test14", "test18"} {"test1", "test2", "test5", "test6", "test9", "test10", "test13", "test16", "test17"} {"test1", "test2", "test5", "test6", "test9", "test10", "test13", "test15", "test17"} {"test1", "test2", "test5", "test6", "test9", "test10", "test14", "test15", "test17"}
等等
我不能從這種方法得到任何語義,你能說明一些示例輸入? –
預期產量是多少? –
我想理想情況下,我將列出有效組以及打印到日誌中的每個有效組。我試圖讓這個例子比問題更簡單。 – Tommo