Simple method without recursion


  • 0
    H

    The basic idea is to insert every character into all possible position in the already generated String List. Use Set to store the results so that there are no duplicates.

    public class Solution { 
        public List<List<Integer>> permuteUnique(int[] num) {
        if(num.length == 0) return null; 
           Set<List<Integer> > record = new HashSet<>();
          int i = 0;
         List<Integer> start = new LinkedList<>();
    
        start.add(num[i++]);
        record.add(start);
         while(i < num.length) {
    
            Set<List<Integer> > newRecord = new HashSet<>();
    
            for(List<Integer> curResult: record) {
                
                for(int j = 0; j < curResult.size();j++){
                    List<Integer> nextResult = new LinkedList<>(curResult);
                    nextResult.add(j,num[i]);
                    newRecord.add(nextResult);
                }
                // add the last one
                List<Integer> nextResult = new LinkedList<>(curResult);
                nextResult.add(num[i]);
                newRecord.add(nextResult);
            }
            record = newRecord;
            i++;
        }
        List<List<Integer> > result = new ArrayList<>(record);
        return result;
    }
    

    }


Log in to reply
 

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