publicclassSolution{ public List<List<Integer>> permute(int[] num) { List<List<Integer>> result = new ArrayList<List<Integer>>(); generate(num, newboolean[num.length], result, new ArrayList<Integer>()); return result; }
privatevoidgenerate(int[] num, boolean[] used, List<List<Integer>> result, List<Integer> permutation){ if (permutation.size() == num.length) { result.add(new ArrayList<Integer>(permutation)); } else { for (int i = 0; i < num.length; i++) { if (!used[i]) { permutation.add(num[i]); used[i] = true; generate(num, used, result, permutation); permutation.remove(permutation.size() - 1); used[i] = false; } } } } }
publicclassSolution{ public List<List<Integer>> permuteUnique(int[] num) { List<List<Integer>> result = new ArrayList<List<Integer>>(); Arrays.sort(num); generate(num, newboolean[num.length], result, new ArrayList<Integer>()); return result; }
privatevoidgenerate(int[] num, boolean[] used, List<List<Integer>> result, List<Integer> permutation){ if (permutation.size() == num.length) { result.add(new ArrayList<Integer>(permutation)); } else { int i = 0; while (i < used.length) { if (!used[i]) { permutation.add(num[i]); used[i] = true; generate(num, used, result, permutation); permutation.remove(permutation.size() - 1); used[i] = false; while (i < used.length - 1 && num[i] == num[i + 1]) { i++; } } i++; } } } }