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 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
| import java.util.*;
public class _47全排列II {
public List<List<Integer>> permuteUnique_gov(int[] nums) { int len = nums.length; List<List<Integer>> res = new ArrayList<>(); List<Integer> output = new ArrayList<>(); Arrays.sort(nums); for (int num : nums) { output.add(num); } backtrack(len, 0, output, res); return res; }
private void backtrack(int len, int index, List<Integer> output, List<List<Integer>> res) { if (index == len) res.add(new ArrayList<>(output)); Set<Integer> set = new HashSet<>(); for (int i = index; i < len; i++) { if (set.contains(output.get(i))) { continue; } set.add(output.get(i)); Collections.swap(output, index, i); backtrack(len, index + 1, output, res); Collections.swap(output, index, i); } }
public List<List<Integer>> permuteUnique(int[] nums) { List<List<Integer>> res = new ArrayList<>(); Map<Integer, Integer> map = new HashMap<>(); for (int num : nums) { if (map.containsKey(num)) { map.put(num, map.get(num) + 1); } else { map.put(num, 1); } }
ArrayList<Integer> keys = new ArrayList<>(map.keySet()); for (Integer key : keys) { List<Integer> list = new ArrayList<>(); list.add(key); update(res, list, key, map); }
return res; }
private void update(List<List<Integer>> res, List<Integer> list, int key, Map<Integer, Integer> map) { Integer counter = map.get(key); if (counter <= 1) { map.remove(key); } else { map.put(key, counter - 1); }
if (map.isEmpty()) { res.add(list); map.put(key, 1); return; }
ArrayList<Integer> keys = new ArrayList<>(map.keySet()); for (Integer nextKey : keys) { List<Integer> listCur = new ArrayList<>(list); listCur.add(nextKey); update(res, listCur, nextKey, map); }
map.put(key, counter); }
public static void main(String[] args) { _47全排列II permutation = new _47全排列II();
System.out.println(permutation.permuteUnique_gov(new int[]{-1, 2, 0, -1, 1, 0, 1}));
} }
|