0047. Permutations II

https://leetcode.com/problems/permutations-ii

Description

Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order.

Example 1:

**Input:** nums = [1,1,2]
**Output:**
[[1,1,2],
 [1,2,1],
 [2,1,1]]

Example 2:

**Input:** nums = [1,2,3]
**Output:** [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

Constraints:

  • 1 <= nums.length <= 8

  • -10 <= nums[i] <= 10

ac

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

    private void backtrack(int[] nums, List<List<Integer>> res, List<Integer> note, boolean[] visiting) {
        // exit, all elements are included
        if (note.size() == nums.length) {
            res.add(new ArrayList<Integer>(note));
            return;
        }

        for (int i = 0; i < nums.length; i++) {
            if (visiting[i] || i > 0 && nums[i] == nums[i-1] && !visiting[i-1]) continue;  // skip duplicate
            note.add(nums[i]);
            visiting[i] = true;
            backtrack(nums, res, note, visiting);
            visiting[i] = false;
            note.remove(note.size()-1);
        }
    }
}

Last updated