Here is my solution to this permutation challenge, I use the DFS Algorithm to build a permutations tree, which I prune depending on the size of the required subset.
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; /** * Permuation Application * This class works out all permutations of a given set of elements * * @author arshadmayet * */ public class Permutation { public static final String EMPTY_STRING = ""; /** * DFS Algorithm to find all permutaions on a sequence of elements * * @param pref path of current element in permutation tree * @param result to store permutations * @param sequence list of elements to permutate * @param subset subset size, use size of sequence for the * entire size per permutation. * @return all permutations of the given sequence as a String List */ public List<String> permutate(String pref, List<String> result, List<String> sequence, int subset) { /* * Get just the unvisited children for tree element */ List<String> diff = sequence.stream().filter(x -> ! (pref).contains(x)).collect(Collectors.toList()); /* * No more children therefore reached end of branch store branch paths */ int limit = sequence.size() - subset; if(diff.size()==limit){ result.add(pref); } /* * Loop thru each child */ for (String s : diff) { if(pref.length()>subset) break; // to trim permuatation tree based on // result sequence limit permutate(pref + s, result,sequence,subset); // recursively traverse //tree } return result; } public static void main(String[] args) { Permutation permutation = new Permutation(); // Test 1 String[] sequenceArray1 = { "1", "2", "3" }; List<String> sequence1 = Arrays.asList(sequenceArray1); int subset1= sequence1.size(); //subset List<String> results1 = permutation.permutate(EMPTY_STRING, new ArrayList<String>(), sequence1, subset1); //Display Logic System.out.println("Test 1"); System.out.println("Sequence "+sequence1); System.out.println("Subset "+subset1); System.out.println(results1); System.out.println("results size = " + results1.size()); System.out.println(); //Test 2 String[] sequenceArray2 = {"1","2","3","4"}; List<String> sequence2 = Arrays.asList(sequenceArray2); int subset2= 2; //subset List<String> results2 = permutation.permutate(EMPTY_STRING, new ArrayList<String>(), sequence2, subset2); //Display Logic System.out.println("Test 2"); System.out.println("Sequence "+sequence2); System.out.println("Subset "+subset2); System.out.println(results2); System.out.println("results size = " + results2.size()); } }
Output:
Test 1
Sequence [1, 2, 3]
Subset 3
[123]
[132]
[213]
[231]
[312]
[321]
results size = 6
Test 2
Sequence [1, 2, 3, 4]
Subset 2
[12]
[13]
[14]
[21]
[23]
[24]
[31]
[32]
[34]
[41]
[42]
[43]
results size = 12