我想找到一種方法來使用遞歸來從具有幾個參數的集合中生成所有元素的獨特組合... 1)我想能夠定義單個組合的大小。 2)我希望能夠從集合中提供我自己的元素(小於提供的大小)以生成包含我提供的元素的所有組合。使用遞歸來獲得具有某些參數的集合的所有組合
由於可能已經令人困惑的輸入是這樣...
輸入:(組元素中,單個組合的大小,提供元素(從0到大小-1)
輸出:所有可能組合的集合(順序無關)
例如,假設我有字母az作爲我提供的元素的集合,我們還要說我希望組合的大小爲5.讓我們也說我爲該方法提供「FG」。
getCombos(Set<V> collection, int size, Set<V> provided)
return Set<Set<V>> combos
下面是它會如何看待與輸入,
getCombos(alphabet, 5, myChars)
這個方法應該返回24 * 23 * 22(12144)獨特的5字母組合,其中包括F和G
這裏是我的嘗試,我覺得這可能是失敗的。
public static <V> HashSet<HashSet<V>> getCombos(HashSet<V> base, HashSet<V> elements, int size) {
HashSet<HashSet<V>> combos = new HashSet<HashSet<V>>();
HashSet<V> curr = new HashSet<V>(base);
recur(curr, combos, base, elements, size);
return combos;
}
public static <V> void recur(HashSet<V> curr, HashSet<HashSet<V>> combos, HashSet<V> base, HashSet<V> elements, int size) {
if (curr.size() == size)
combos.add(curr);
else
for (V v : elements) {
curr.add(v);
recur(curr, combos, base, elements, size);
// This part below is where i feel like i'm going wrong and i'm not sure what to do
curr = dupe(base);
break;
}
}
你有什麼試過? – m0skit0
我加了我試過的東西。 –
'F'和'G'可以在結果中的任何位置? E.G.,都是'FABCG','GCFWA'好的輸出嗎? –