Backtracking
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| class Solution { public List<List<Integer>> permuteUnique(int[] nums) { List<List<Integer>> resultList = new ArrayList<>(); dfs(resultList, nums, 0); return resultList; }
private void dfs(List<List<Integer>> resultList, int[] nums, int levelIndex) { if (levelIndex == nums.length - 1) { List<Integer> numList = new ArrayList<>(nums.length); for (int num : nums) { numList.add(num); } resultList.add(numList); return; }
Set<Integer> set = new HashSet<>(); for (int i = levelIndex; i < nums.length; i++) { if (!set.add(nums[i])) { continue; }
swap(nums, i, levelIndex); dfs(resultList, nums, levelIndex + 1); swap(nums, i, levelIndex); } }
private void swap(int[] nums, int i, int j) { int tmp = nums[i]; nums[i] = nums[j]; nums[j] = tmp; } }
|
Backtracking
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| class Solution { public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> resultList = new ArrayList<>(); List<Integer> numList = new ArrayList<>(nums.length); boolean[] used = new boolean[nums.length]; Arrays.sort(nums); backtrack(resultList, numList, nums, used); return resultList; }
private void backtrack(List<List<Integer>> resultList, List<Integer> numList, int[] nums, boolean[] used) { if (numList.size() == nums.length) { resultList.add(new ArrayList<>(numList)); return; }
for (int i = 0; i < nums.length; i++) { if (used[i]) { continue; }
if (i > 0 && nums[i] == nums[i - 1] && used[i - 1] == false) { continue; }
numList.add(nums[i]); used[i] = true; backtrack(resultList, numList, nums, used); numList.remove(numList.size() - 1); used[i] = false; } } }
|
References
47. Permutations II
剑指 Offer 38. 字符串的排列
剑指 Offer II 084. 含有重复元素集合的全排列