Short Java O(1) extra space solution


  • 1
    A
    private List<List<Integer>> res = new ArrayList<List<Integer>>();
    private ArrayList<Integer> per = new ArrayList<Integer>();
    
    public List<List<Integer>> permuteUnique(int[] num) {
        Arrays.sort(num);
        for(int n:num) per.add(n);
        getPer(0);
        return res;
    }
    
    void getPer(int index) {
        if( index >= per.size()-1 ) {
            res.add((ArrayList<Integer>)per.clone());
            return;
        }
        Integer previous = null;
        for( int i=per.size()-index; i>0; i-- ) {
            if( per.get(index) != previous ) getPer(index+1);
            per.add(previous = per.remove(index));
        }
    }

Log in to reply
 

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