La ricorsione è tuo amico per questo compito.
Per ogni elemento: "indovina" se si trova nel sottoinsieme corrente e richiama ricorsivamente con l'ipotesi e un superset più piccolo da cui è possibile selezionare. Farlo per entrambe le ipotesi "sì" e "no" comporterà tutti i possibili sottoinsiemi.
Il trattenimento di una certa lunghezza può essere facilmente eseguito in una clausola di arresto. Codice
Java:
private static void getSubsets(List<Integer> superSet, int k, int idx, Set<Integer> current,List<Set<Integer>> solution) {
//successful stop clause
if (current.size() == k) {
solution.add(new HashSet<>(current));
return;
}
//unseccessful stop clause
if (idx == superSet.size()) return;
Integer x = superSet.get(idx);
current.add(x);
//"guess" x is in the subset
getSubsets(superSet, k, idx+1, current, solution);
current.remove(x);
//"guess" x is not in the subset
getSubsets(superSet, k, idx+1, current, solution);
}
public static List<Set<Integer>> getSubsets(List<Integer> superSet, int k) {
List<Set<Integer>> res = new ArrayList<>();
getSubsets(superSet, k, 0, new HashSet<Integer>(), res);
return res;
}
Invocare con:
List<Integer> superSet = new ArrayList<>();
superSet.add(1);
superSet.add(2);
superSet.add(3);
superSet.add(4);
System.out.println(getSubsets(superSet,2));
produrrà:
[[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
prego vedere un altro filo con la stessa domanda e un metodo alternativo per la soluzione: http://stackoverflow.com/questions/127704/algorithm-to-return-all-combinations-of-k-elements- da-n/42190945 # 42190945 (può essere convertito prontamente da C# a Java) – jacoblambert