There is a code that iterates through all possible combinations of the List<Integer> elements:
import java.util.Arrays; import java.util.Collections; import java.util.List; public class Permute_sout { static void permute(List<Integer> arr, int k) { for (int i = k; i < arr.size(); i++) { Collections.swap(arr, i, k); permute(arr, k + 1); Collections.swap(arr, k, i); } if (k == arr.size() - 1) { System.out.println(Arrays.toString(arr.toArray())); } } static void permute(List<Integer> arr) { permute(arr, 0); } public static void main(String[] args) { permute(Arrays.asList(1, 2, 3)); } } I need to change the permute method so that it does not output data to the console, but returns a List<List<Integer>> :
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; public class Permute { private static List<List<Integer>> lists = new ArrayList<>(); static List<List<Integer>> permute(List<Integer> arr, int k) { for (int i = k; i < arr.size(); i++) { Collections.swap(arr, i, k); permute(arr, k + 1); Collections.swap(arr, k, i); } if (k == arr.size() - 1) { lists.add(arr); //добавление в список комбинаций } return lists; } static List<List<Integer>> permute(List<Integer> arr) { return permute(arr, 0); } public static void main(String[] args) { System.out.println(permute(Arrays.asList(1, 2, 3))); } } However, this code writes to all List<List<Integer>> elements only the first List<Integer> of the search. Where is the mistake?
[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]instead of the required[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 2, 1], [3, 1, 2]]can not be called true. More precisely, can not be called such as required. - Regent