【leetcode】第47题 Permutations II(非递归法)题目+解析+代码

来源:互联网 发布:淘宝指南针运动 编辑:程序博客网 时间:2024/06/06 03:40

【题目】

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

For example,
[1,1,2] have the following unique permutations:

[  [1,1,2],  [1,2,1],  [2,1,1]]
【解析】

这个题和上一题几乎一样,这里使用非递归法解答,递归法参照第46题即可解答。

【代码】

public List<List<Integer>> permuteUnique(int[] nums) {        LinkedList<List<Integer>> res = new LinkedList<List<Integer>>();        int n = nums.length;        Arrays.sort(nums);        List<Integer> temp = new ArrayList<Integer>();        for(int b:nums)            temp.add(b);        res.add(temp);        while(true)        {            int count=-1;            for(int i=n-1;i>0;i--)                if(nums[i-1]<nums[i])                {                    count=i-1;                    break;                }            if(count==-1)                return res;            for(int i=n-1;i>count;i--)                if(nums[i]>nums[count])                {                    swap(nums,count,i);                    break;                }            perm(nums,count+1,n-1);            List<Integer> tempList = new ArrayList<Integer>();            for(int b:nums)                tempList.add(b);            res.add(tempList);        }    }    public static void swap(int[] nums,int p,int q){        int temp=nums[p];        nums[p]=nums[q];        nums[q]=temp;    }    public static void perm(int[] nums,int p,int q){        for(int left=p,right=q;left<right;left++,right--)        {            int temp=nums[left];            nums[left]=nums[right];            nums[right]=temp;        }    }


原创粉丝点击