Given a collection of numbers that might contain duplicates, return all possible unique permutations.
For example,[1,1,2]
have the following unique permutations:[1,1,2]
, [1,2,1]
, and [2,1,1]
.
题目大意:给一个数组,包含重复元素,返回所有可能组合,去重。
解题思路:这题是Permutation的变种,思路就是回溯。首先把数组排序一下,对于不是第一次使用的数字,检测是否出现过。
public List<List<Integer>> permuteUnique(int[] nums) { List<List<Integer>> res = new ArrayList<>(); if (nums == null || nums.length == 0) { return res; } Arrays.sort(nums); List<Integer> tmp = new ArrayList<>(); boolean[] used = new boolean[nums.length]; helper(res, tmp, 0, nums.length, nums, used); return res; } public void helper(List<List<Integer>> res, List<Integer> tmp, int n, int N, int[] nums, boolean[] used) { if (n == N) { res.add(new ArrayList<>(tmp)); return; } int last_num = 0x80000000; for (int i = 0; i < N; i++) { if (!used[i] && last_num != nums[i]) { used[i] = true; tmp.add(nums[i]); last_num = nums[i]; helper(res, tmp, n + 1, N, nums, used); used[i] = false; tmp.remove(tmp.size() - 1); } } }