LeetCode_47 Permutations II

Link to original problem: 这里写链接内容

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].

Related Problem:
46 Permutations: 这里写链接内容

本题需要考虑的比46 Permutations略微复杂了一些,因为这里的输入不再是1到n了,而是一个任意给定的整数数组,需要我们考虑避免重复的问题。

跳过重复的idea比较简单,即先排序,使用排序好的数组。如果遇到某个元素,其值跟上一个数字相同,但是上一个数字并未放入背包,那么这个数字也不能放入背包,需要跳过。

下面是具体代码:

public class Solution {
    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        if(nums == null || nums.length == 0) return res;
        Arrays.sort(nums);
        List<Integer> cur = new ArrayList<Integer>();
        boolean[] used = new boolean[nums.length];
        helper(res, cur, nums, used, 0);
        return res;
    }
    private void helper(List<List<Integer>> res, List<Integer> cur, int[] nums, boolean[] used, int count){
        if(count == nums.length){
            res.add(new ArrayList<Integer>(cur));
            return;
        }
        for(int ii = 0; ii < nums.length; ii++){
            if(used[ii] == false){
                if(ii > 0 && (nums[ii] == nums[ii-1] && used[ii-1] == false)) continue;
                cur.add(nums[ii]);
                used[ii] = true;
                helper(res, cur, nums, used, count+1);
                cur.remove(cur.size()-1);
                used[ii] = false;
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值