Googling lead me to this question. I found the method below than other methods.
I mainly use Set for recursively generating permutations. To illustrate: the first position can contain all possible values, the second - all possible values, except the first, and so on. When we get to the last position, there is only one possibility.
From the point of view of the parameters of the recursive function, (1) we transfer what has already been written as a current string. (2) We pass an Arraylist that contains the results - list_of_permutes (3) We pass a set from which you can select the current number - currentnums. At the last level, we have a complete permutation, which is then added to the list array - list_of_permutes and returns up.
public static ArrayList recurse_nums(Set<Integer> currentnums, String currentstring, ArrayList list_of_permutes){ if(currentnums.size()==1){ int elem = currentnums.iterator().next(); list_of_permutes.add(currentstring + Integer.toString(elem)); return list_of_permutes; } for(int a:currentnums){ String newstring = currentstring + a; Set<Integer> newnums = new HashSet<>(); newnums.addAll(currentnums); newnums.remove(a); recurse_nums(newnums, newstring,list_of_permutes); } return list_of_permutes; }
This may be caused by something like the following:
public static ArrayList permute_array(int[] arr){ Set<Integer> currentnums = new HashSet<>(); for (int i = 0; i < arr.length; i++) {currentnums.add(arr[i]);} ArrayList permutations = new ArrayList(); recurse_nums(currentnums,"",permutations); return permutations; }
source share