Java non-recursive solution.


  • 0
    J
    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> res=new ArrayList<List<Integer>>();
        if(nums.length==0) return res;
        res.add(new ArrayList<Integer>());
        for(int n:nums){
            List<List<Integer>> next=new ArrayList<List<Integer>>();
            for(List<Integer> list:res){
                for(int i=0;i<=list.size();i++){
                    List<Integer> nextList=new ArrayList<Integer>(list);
                    if(i==list.size()) {nextList.add(n); next.add(nextList); break;}
                    nextList.add(i,n);
                    next.add(nextList);
                    if(list.get(i)==n) break;
                }
            }
            res=next;
        }
        return res;
    }

  • 0
    S

    I'm confuse about why add the condition of list.get(i) == n can remove the duplicates? Can you explain it for me please?


Log in to reply
 

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