Easy Iterative Solution Similar with Permutations I

  • 3
       The solution is similar with permutations I problem, but added a condition
        Method: repetition numbers only have one permutation, e.g. [1,1,1,1].
           so each time only adding a number to the left of its repetition
           e.g. [1,2] --> [1,1,2] -->then stop. 
    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> ret = new ArrayList<List<Integer>>();
        ret.add(new ArrayList<Integer>());
        for(int i=0; i<nums.length; i++){
            List<List<Integer>> save = new ArrayList<List<Integer>>();
            for(List<Integer> lst: ret){
                for(int j=0; j<=lst.size(); j++){
                    if(j != 0 && lst.get(j-1) == nums[i]) // stop here
                    List<Integer> l = new ArrayList<Integer>(lst);
                    l.add(j, nums[i]);
            ret = save;
        return ret;

Log in to reply

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