|
| 1 | +package com.baeldung.algorithms.combinatorics; |
| 2 | + |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +import static java.util.Collections.swap; |
| 6 | + |
| 7 | +public class Combinatorics { |
| 8 | + |
| 9 | + public static List<List<Integer>> permutations(List<Integer> sequence) { |
| 10 | + List<List<Integer>> results = new ArrayList<>(); |
| 11 | + permutationsInternal(sequence, results, 0); |
| 12 | + return results; |
| 13 | + } |
| 14 | + |
| 15 | + private static void permutationsInternal(List<Integer> sequence, List<List<Integer>> results, int index) { |
| 16 | + if (index == sequence.size() - 1) { |
| 17 | + results.add(new ArrayList<>(sequence)); |
| 18 | + } |
| 19 | + |
| 20 | + for (int i = index; i < sequence.size(); i++) { |
| 21 | + swap(sequence, i, index); |
| 22 | + permutationsInternal(sequence, results, index + 1); |
| 23 | + swap(sequence, i, index); |
| 24 | + } |
| 25 | + } |
| 26 | + |
| 27 | + public static List<List<Integer>> combinations(List<Integer> inputSet, int k) { |
| 28 | + List<List<Integer>> results = new ArrayList<>(); |
| 29 | + combinationsInternal(inputSet, k, results, new ArrayList<>(), 0); |
| 30 | + return results; |
| 31 | + } |
| 32 | + |
| 33 | + private static void combinationsInternal( |
| 34 | + List<Integer> inputSet, int k, List<List<Integer>> results, ArrayList<Integer> accumulator, int index) { |
| 35 | + int leftToAccumulate = k - accumulator.size(); |
| 36 | + int possibleToAcculumate = inputSet.size() - index; |
| 37 | + |
| 38 | + if (accumulator.size() == k) { |
| 39 | + results.add(new ArrayList<>(accumulator)); |
| 40 | + } else if (leftToAccumulate <= possibleToAcculumate) { |
| 41 | + combinationsInternal(inputSet, k, results, accumulator, index + 1); |
| 42 | + |
| 43 | + accumulator.add(inputSet.get(index)); |
| 44 | + combinationsInternal(inputSet, k, results, accumulator, index + 1); |
| 45 | + accumulator.remove(accumulator.size() - 1); |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + public static List<List<Character>> powerSet(List<Character> sequence) { |
| 50 | + List<List<Character>> results = new ArrayList<>(); |
| 51 | + powerSetInternal(sequence, results, new ArrayList<>(), 0); |
| 52 | + return results; |
| 53 | + } |
| 54 | + |
| 55 | + private static void powerSetInternal( |
| 56 | + List<Character> set, List<List<Character>> powerSet, List<Character> accumulator, int index) { |
| 57 | + if (index == set.size()) { |
| 58 | + powerSet.add(new ArrayList<>(accumulator)); |
| 59 | + } else { |
| 60 | + accumulator.add(set.get(index)); |
| 61 | + |
| 62 | + powerSetInternal(set, powerSet, accumulator, index + 1); |
| 63 | + accumulator.remove(accumulator.size() - 1); |
| 64 | + powerSetInternal(set, powerSet, accumulator, index + 1); |
| 65 | + } |
| 66 | + } |
| 67 | +} |
0 commit comments