LeetCode:Permutations II

Permutations II




Total Accepted: 71670  Total Submissions: 254494  Difficulty: Medium

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], and [2,1,1].

Subscribe to see which companies asked this question

Hide Tags
  Backtracking



















思路:

承接上一【LeetCode:Permutations】

由于全排列就是从第一个数字起每个数分别与它后面的数字交换。我们先尝试加个这样的判断——如果一个数与后面的数字相同那么这二个数就不交换了。如122,第一个数与后面交换得212、221。然后122中第二数就不用与第三个数交换了,但对212,它第二个数与第三个数是不相同的,交换之后得到221。与由122中第一个数与第三个数交换所得的221重复了。所以这个方法不行。

换种思维,对122,第一个数1与第二个数2交换得到212,然后考虑第一个数1与第三个数2交换,此时由于第三个数等于第二个数,所以第一个数不再与第三个数交换。再考虑212,它的第二个数与第三个数交换可以得到解决221。此时全排列生成完毕。
这样我们也得到了在全排列中去掉重复的规则——去重的全排列就是从第一个数字起每个数分别与它后面非重复出现的数字交换



java code:

public class Solution {
    public List<List<Integer>> permuteUnique(int[] nums) {
        
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        
        permute(res, nums, 0);
        
        return res;
    }
    
    
    // 自定义函数    
    void permuteUnique(List<List<Integer>> res, int[] nums, int pos) {
        if(pos == nums.length) {
            
            ArrayList<Integer> list = new ArrayList<Integer>();
            for(int num:nums) list.add(num);
            
            res.add(list);
            return;
        }
        
        for(int i=pos;i<nums.length;i++){
            if(isSwap(nums,pos,i)) {
                swap(nums, pos,i);
                permute(res,nums,pos+1);
                swap(nums, pos,i);
            }
        }
    }
    
    void swap(int[] nums, int i, int j) {
        int t = nums[i];
    	nums[i] = nums[j];
    	nums[j] = t;
    }
    
    boolean isSwap(int[] nums, int lo, int hi) {
        for(int i=lo;i<hi;i++) {
            if(nums[i]==nums[hi]) return false;
        }
        return true;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值