An easy understanding java solution without using flag


  • 0
    L
    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> permutations=new ArrayList<>();
        if(nums.length==0){
            return permutations;
        }
        Arrays.sort(nums);
        List<Integer> choices=Arrays.stream(nums).boxed().collect(Collectors.toList());
        append(permutations,new ArrayList<Integer>(),choices);
        return permutations;
    }
    
    public void append(List<List<Integer>> permutations,List<Integer> permutation,List<Integer> choices){
            for(int i=0;i<choices.size();i++){
                if(i>0 && choices.get(i)==choices.get(i-1)){
                    continue;
                }
                List<Integer> appendedPermutation=new ArrayList<>(permutation);
                appendedPermutation.add(choices.get(i));
                List<Integer> updatedChoices=new ArrayList<>(choices);
                updatedChoices.remove(i);
                if(updatedChoices.isEmpty()){
                    permutations.add(appendedPermutation);
                }else{
                    append(permutations,appendedPermutation,updatedChoices);
                }
            }
    }

Log in to reply
 

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