47 Permutations II

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

2. Implementation

(2) Backtracking

class Solution {
    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> permutation = new ArrayList<>();
        boolean[] used = new boolean[nums.length];
        Arrays.sort(nums);
        getPermutation(nums, used, permutation, res);
        return res;
    }

    public void getPermutation(int[] nums, boolean[] used, List<Integer> permutation, List<List<Integer>> res) {
        if (permutation.size() == nums.length) {
            res.add(new ArrayList<>(permutation));
            return;
        }

        for (int i = 0; i < nums.length; i++) {
            if (i > 0 && nums[i - 1] == nums[i] && !used[i - 1]) {
                continue;
            }

            if (!used[i]) {
                used[i] = true;
                permutation.add(nums[i]);
                getPermutation(nums, used, permutation, res);
                permutation.remove(permutation.size() - 1);
                used[i] = false;
            }
        }
    }
}

3. Time & Space Complexity

Backtracking: 时间复杂度O(n!), 空间复杂度O(n!)

Last updated