My java solution - recursive


  • 0
    O

    Like generating permutations, only that at every level i keep track of values that i've already used. If a value has been used at a level it will be ignored ( at that level )

    public class Solution {
    public List<List<Integer>> solutionsPermU = new LinkedList<>();

    public void generate(List<Integer> sol, List<Integer> set){
            if( set.isEmpty()){
                solutionsPermU.add(sol);
                return;
            }
            HashSet<Integer> used = new HashSet<>();
            for(int i = 0 ; i < set.size(); i++){
                if(used.contains(set.get(i)))
                    continue;
                used.add(set.get(i));
                List<Integer> solC = (List<Integer>) ((LinkedList<Integer>) sol).clone();
                solC.add(set.get(i));
                int v = set.remove(i);
                generate(solC, set);
                set.add(i,v);
            }
        }
        
    public  List<List<Integer>> permuteUnique(int[] num) {
            LinkedList<Integer> set = new LinkedList<>();
            for(int i = 0 ; i < num.length; i++)
            	set.add(num[i]);
            generate(new LinkedList(), set);
           
            return solutionsPermU;
    }
    

    }


Log in to reply
 

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