Permutations II

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. [
  2. [1,1,2],
  3. [1,2,1],
  4. [2,1,1]
  5. ]

Solution:

  1. public class Solution {
  2. public List<List<Integer>> permuteUnique(int[] nums) {
  3. Arrays.sort(nums);
  4. List<List<Integer>> res = new ArrayList<List<Integer>>();
  5. boolean[] used = new boolean[nums.length];
  6. helper(nums, used, new ArrayList<Integer>(), res);
  7. return res;
  8. }
  9. private void helper(int[] nums, boolean[] used, List<Integer> sol, List<List<Integer>> res) {
  10. if (sol.size() == nums.length) {
  11. res.add(new ArrayList<Integer>(sol));
  12. return;
  13. }
  14. for (int i = 0; i < nums.length; i++) {
  15. // avoid duplication
  16. if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) {
  17. continue;
  18. }
  19. if (!used[i]) {
  20. used[i] = true;
  21. sol.add(nums[i]);
  22. helper(nums, used, sol, res);
  23. sol.remove(sol.size() - 1);
  24. used[i] = false;
  25. }
  26. }
  27. }
  28. }