Simple Java Solution using Set.


  • 0
    S

    The idea is same as discussed in this problem.
    The only difference is that before inserting the current list in the final result we also check if we can insert the String form of this list in a set.

    https://leetcode.com/problems/permutations

    public class Solution {
        public List<List<Integer>> permuteUnique(int[] nums) {
            Arrays.sort(nums);
            return helper(nums,0);
        }
        
        List<List<Integer>> helper(int[] nums, int index){
            List<List<Integer>> result=new ArrayList();
            if(index==nums.length){
                List<Integer> curr=new ArrayList();
                result.add(curr);
                return result;
            }
            
            List<List<Integer>> prev=helper(nums, index+1);
            Set<String> cache=new HashSet();
            
            for(List<Integer> list: prev){
                for(int i=0; i<=list.size(); i++){
                    List<Integer> newList=new ArrayList(list);
                    newList.add(i,nums[index]);
                    if(cache.add(newList.toString()))
                        result.add(newList);
                }
            }
            return result;
        }
        
    }

Log in to reply
 

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