|
| 1 | +package com.thealgorithms.backtracking; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.List; |
| 5 | + |
| 6 | +/** |
| 7 | + * Class generates all subsequences for a given list of elements using backtracking |
| 8 | + */ |
| 9 | +public class Subsequence { |
| 10 | + /** |
| 11 | + * Find all subsequences of given list using backtracking |
| 12 | + * |
| 13 | + * @param sequence a list of items on the basis of which we need to generate all subsequences |
| 14 | + * @param <T> the type of elements in the array |
| 15 | + * @return a list of all subsequences |
| 16 | + */ |
| 17 | + public static <T> List<List<T>> generateAllSubsequences(List<T> sequence) { |
| 18 | + List<List<T>> allSubSequences = new ArrayList<>(); |
| 19 | + if (sequence.isEmpty()) { |
| 20 | + allSubSequences.add(new ArrayList<>()); |
| 21 | + return allSubSequences; |
| 22 | + } |
| 23 | + List<T> currentSubsequence = new ArrayList<>(); |
| 24 | + backtrack(sequence, currentSubsequence, 0, allSubSequences); |
| 25 | + return allSubSequences; |
| 26 | + } |
| 27 | + |
| 28 | + /** |
| 29 | + * Iterate through each branch of states |
| 30 | + * We know that each state has exactly two branching |
| 31 | + * It terminates when it reaches the end of the given sequence |
| 32 | + * |
| 33 | + * @param sequence all elements |
| 34 | + * @param currentSubsequence current subsequence |
| 35 | + * @param index current index |
| 36 | + * @param allSubSequences contains all sequences |
| 37 | + * @param <T> the type of elements which we generate |
| 38 | + */ |
| 39 | + private static <T> void backtrack(List<T> sequence, List<T> currentSubsequence, int index, List<List<T>> allSubSequences) { |
| 40 | + if (index == sequence.size()) { |
| 41 | + allSubSequences.add(new ArrayList<>(currentSubsequence)); |
| 42 | + return; |
| 43 | + } |
| 44 | + |
| 45 | + backtrack(sequence, currentSubsequence, index + 1, allSubSequences); |
| 46 | + currentSubsequence.add(sequence.get(index)); |
| 47 | + backtrack(sequence, currentSubsequence, index + 1, allSubSequences); |
| 48 | + currentSubsequence.removeLast(); |
| 49 | + } |
| 50 | +} |
0 commit comments