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

Solution

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

    public void permutae(List<List<Integer>> result, int[] nums, int[] visited, List<Integer> current) {
        if (current.size() == nums.length) {
            result.add(new ArrayList<Integer>(current));
            return;
        }

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

            visited[i] = 1;
            current.add(nums[i]);
            permutae(result, nums, visited, current);
            current.remove(current.size() - 1);
            visited[i] = 0;
        }
    }    

}

results matching ""

    No results matching ""