LeetCode, leetcodeoj
Question:
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].
Ideas:
1) The permutation code can be used directly to remove repeated returns Using the list. contains (o) method.TrueIf and only if this list contains at least one elementESuch that(O = null? E = null: o. equals (e ))]
2) Like Permutation, after sorting, we will continue to see the plug-in. In case of repetition, we will only insert the plug-in front of this value and then break the AK. Why? Because the formed set has symmetry, we only insert it on the left of the duplicate value. Of course, you can also insert only to the right of the duplicate value.
package permutation;import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class PermutationsII { public List<List<Integer>> permuteUnique(int[] nums) { List<List<Integer>> res = new ArrayList<List<Integer>>(); Arrays.sort(nums); List<Integer> subRes = new ArrayList<Integer>(); subRes.add(nums[0]); res.add(subRes); return permute(res, nums, 1); } private List<List<Integer>> permute(List<List<Integer>> res, int[] nums, int pos) { if (pos >= nums.length) return res; List<List<Integer>> newRes = new ArrayList<List<Integer>>(); for (List<Integer> subRes : res) { int count = subRes.size(); for (int i = 0; i <= count; ++i) { if (i > 0 && nums[pos] == subRes.get(i - 1)) break; List<Integer> newSubRes = new ArrayList<Integer>(subRes); newSubRes.add(i, nums[pos]); newRes.add(newSubRes); } } return permute(newRes, nums, pos + 1); } public static void main(String[] args) { // TODO Auto-generated method stub PermutationsII p = new PermutationsII(); int[] nums = { 2,2,1,1 }; List<List<Integer>> res = p.permuteUnique(nums); for (List<Integer> l : res) { for (int i : l) System.out.print(i + "\t"); System.out.println(); } }}