47. Permutations II

class Solution {
    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> ans = new ArrayList<>();
        if (nums == null || nums.length == 0) return ans;
        boolean[] used = new boolean[nums.length];
        Arrays.sort(nums);

        dfs(nums, used, new ArrayList<>(), ans);

        return ans;
    }

    private void dfs(int[] nums, boolean[] used, List<Integer> path, List<List<Integer>> ans){
        if (path.size() == nums.length){
            ans.add(new ArrayList<>(path));
            return;
        }

        for (int i = 0; i < nums.length; i++){
            if (used[i]) continue;
            if (i - 1 >= 0 && !used[i - 1] && nums[i - 1] == nums[i]) continue;
            used[i] = true;
            path.add(nums[i]);
            dfs(nums, used, path, ans);
            used[i] = false;
            path.remove(path.size() - 1);
        }
    }
}

results for ""

    No results matching ""