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

【题目】

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;
        }
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值