Java concise recursive solution.


  • 0
    C
    public List<List<Integer>> permuteUnique(int[] nums) {
        boolean[] visited = new boolean[nums.length];
        Arrays.sort(nums);
        List<List<Integer>> ret = new ArrayList<>();
        dfs(nums, visited, new ArrayList<>(), ret);
        return ret;
    }
    
    private void dfs(int[] nums, boolean[] visited, List<Integer> path, List<List<Integer>> ret) {
        if (path.size() == nums.length) {
            ret.add(path);
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (visited[i] || (i > 0 && nums[i] == nums[i-1] && !visited[i-1])) {
                continue;   // remove duplicates
            }
            List<Integer> p = new ArrayList<>(path);
            p.add(nums[i]);
            visited[i] = true;
            dfs(nums, visited, p, ret);
            visited[i] = false;  // recover
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.