47. Permutations II (Medium)

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

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

Example:

Input: [1,1,2]
Output:
[
  [1,1,2],
  [1,2,1],
  [2,1,1]
]

Hints

Solutions

  • Java
class Solution {
    Set<String> uniqueHash = new HashSet<>();

    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> rst = new ArrayList<>();
        if (nums == null || nums.length == 0) {
            return rst;
        }

        Arrays.sort(nums);
        doPermutation(nums, rst, 0);

        return rst;
    }

    void swap(int[] nums, int x, int y) {
        int tmp = nums[x];
        nums[x] = nums[y];
        nums[y] = tmp;
    }

    private void doPermutation(int[] nums, List<List<Integer>> rst, int depth) {
        int len = nums.length;

        if (depth == len - 1) {
            List<Integer> solution = new ArrayList<>();
            for (int n : nums) {
                solution.add(n);
            }

            if (!uniqueHash.contains(solution.toString())) {
                rst.add(solution);
                uniqueHash.add(solution.toString());
            }

            return;
        }

        for (int j = depth; j < len; j++) {
            if (j != depth && nums[j] == nums[depth]) {
                continue;
            }

            swap(nums, depth, j);
            doPermutation(nums, rst, depth + 1);
            swap(nums, depth, j);
        }
    }
}
class Solution2 {
    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> rst = new ArrayList<>();
        Arrays.sort(nums);
        doPermutation(nums, rst, 0);
        return rst;
    }

    void swap(int[] a, int i, int j) {
        int tmp = a[i];
        a[i] = a[j];
        a[j] = tmp;
    }

    void doPermutation(int[] nums, List<List<Integer>> rst, int depth) {
        if (depth == nums.length - 1) {
            List<Integer> list = new ArrayList<>();
            for (int n : nums) {
                list.add(n);
            }
            rst.add(list);

            return;
        }

        for (int j = depth, l = nums.length; j < l; j++) {
            if (j > depth && nums[j] == nums[depth]) {
                continue;
            }

                swap(nums, depth, j);
                doPermutation(Arrays.copyOf(nums, nums.length), rst, depth);
            }
        }
    }
Copyright © iovi.com 2017 all right reserved,powered by GitbookLast Modification: 2019-04-21 21:13:27

results matching ""

    No results matching ""