Permutations II

Given a list of numbers with duplicate number in it. Find all unique permutations.

class Solution {
    /** * @param nums: A list of integers. * @return: A list of unique permutations. */
    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> results = new ArrayList<>();
        if (nums == null) {
            return results;
        }
        if (nums.length == 0) {
            results.add(new ArrayList<Integer>());
            return results;
        }
        List<Integer> result = new ArrayList<>();
        Set<List<Integer>> hash = new HashSet<>();
        int[] visited = new int[nums.length];
        dfsHelper(nums, visited, results, result, hash);
        return results;
    }
    private void dfsHelper(int[] nums,
                           int[] visited,
                           List<List<Integer>> results,
                           List<Integer> result,
                           Set<List<Integer>> hash) {
        if (result.size() == nums.length ) {
            List<Integer> temp = new ArrayList<Integer>(result);
            if (!hash.contains(temp)) {
                results.add(temp);
                hash.add(temp);
            }
        }
        for (int i = 0; i < nums.length; i++) {
            if (visited[i] == 1) {
                continue;
            }
            result.add(nums[i]);
            visited[i] = 1;
            dfsHelper(nums, visited, results, result, hash);
            result.remove(result.size() - 1);
            visited[i] = 0;
        }
    }
}


点赞