privatestaticclassSolution2{ public List<List<Integer>> permute(int[] nums) { int len = nums.length; List<List<Integer>> res = new ArrayList<>(); if (len == 0) { return res; } boolean[] used = newboolean[len]; Deque<Integer> path = new ArrayDeque<>(len); dfs(nums, 0, len - 1, res); return res; }
publicstaticvoiddfs(int[] array, int start, int end, List<List<Integer>> res){ if (start == end) { List<Integer> temp = new ArrayList<>(); for (int j : array) { temp.add(j); } res.add(temp); } else { for (int i = start; i <= end; i++) { //1,2,3的全排列这块相当于将其中一个提了出来,下次递归从start+1开始 swap(array, start, i); dfs(array, start + 1, end, res); //这块是复原数组,为了保证下次另外的同级递归使用数组不会出错 //这块可以通过树来理解,每次回退一步操作,交换回去 swap(array, start, i); } } } publicstaticvoidswap(int[] array, int i, int j){ int temp = array[i]; array[i] = array[j]; array[j] = temp; }