我正在抓我的頭試圖做到這一點,它讓我吃了起來。我知道這並不複雜。我有一些項目,這個數字可以等於或大於三。然後我需要確定將完成總計的一組項目的可能組合。唯一的限制就是團體應該有三件或更多的物品,不超過(但包括)七件物品。確定可能的項目羣的算法
例如:
如果我有7個項目,然後我可以有這些可能的組:
- 1組7項。
- 1組4件商品和1組3件商品。
如果我有12個項目,我可以有這些可能的組:
- 4組,每組3個項目。
- 3組4項。
- 2組6件商品。
- 1組7件商品+ 1組5件商品。
- 2組3個和1組6個項目。
- 1組3,1組4,1組5項。
- ...
我想到了遞歸和開始實施的算法。這顯然不起作用。我吮吸遞歸。很多。
//Instance Fields
public List<ArrayList<String>> options;
//Method that will generate the options. The different options are
//stored in a list of "option". An individual option will store a list of
//strings with the individual groups.
public void generateOptions(int items, ArrayList<String> currentOption){
//If the current option is null, then create a new option.
if(currentOption == null){
currentOption = new ArrayList<String>();
}
if(items < 3){
//If the number of items is less than three then it doesn't comply with the
//requirements (teams should be more or equal than three.
currentOption.add("1 group of "+items+" items");
options.add(currentOption);
}
else{
//I can make groups of 3,4,5,6 and 7 items.
for(int i = 3;i<=7;i++){
if(items%i == 0){
// If the number of items is divisible per the current number,
// then a possible option could be items/i groups of i items.
// Example: Items = 9. A possible option is 3 groups of 3 items.
currentOption.add(items/i +" groups of "+ i+" items");
options.add(currentOption);
}
else{
// If the number of items - the current number is equal or greater than
// three, then a possible option could be a group of i items
// and then I'll have items-i items to separate in other groups.
if(items - i >=3){
currentOption.add("1 group of "+i+" items");
generateOptions(items-i,currentOption);
}
}
}
}
}
感謝您的幫助!
這與我所看到的非常接近。我試圖將其轉換爲Java以查看它是如何工作的。謝謝。 – miguelrios 2010-01-25 07:01:05