#47 Permutations II

Description

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

Example

Input: [1,1,2]
Output: [ [1,1,2], [1,2,1], [2,1,1] ]

解题思路

承接46
注意把函数中now remove的时候不要用remove(Object obj),用remove(int index),因为这次里面有重复的数字
然后在最后加个去重(List 转 Set)

class Solution {
    public void getList(List<Integer> now, List<List<Integer>> all, List<Integer> cur){
        if(cur.isEmpty()){
            all.add(new ArrayList<>(now));
            return;
        }
        for(int i = 0; i < cur.size(); i++){
            Integer temp = cur.get(i);
            cur.remove(i);
            now.add(temp);
            getList(now, all, cur);
            cur.add(i, temp);
            now.remove(now.size() - 1);
        }
    }
    public List<List<Integer>> permuteUnique(int[] nums) {
        List<Integer> s = new ArrayList<>();
        for(int i = 0; i < nums.length; i++){
            s.add(nums[i]);
        }
        List<Integer> now = new ArrayList<>();
        List<List<Integer>> all = new ArrayList<>();
        getList(now, all, s);
        //return all;
        return new ArrayList<>(new HashSet(all));
    }
}

emmmm一种比较好的方法是不用每次移来移去,设置一个boolean的visit数组用来存放是否被访问
然后在最开始的时候,对数组进行排序,让相同的数字位于同一地方,这样在更新的时候,碰到相同的数字,只要移动到不同数字的地方再往后递归,就不需要进行去重的操作。

class Solution {
    public List<List<Integer>> permuteUnique(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> res = new ArrayList<>();
        permutation(nums, res, new ArrayList<Integer>(), new boolean[nums.length]);
        return res;
    }
    
    private void permutation(int[] nums, List<List<Integer>> res, List<Integer> tmp, boolean[] visited) {
        if (tmp.size() == nums.length) {
            res.add(new ArrayList<>(tmp)); 
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if(visited[i] || (i > 0 && !visited[i - 1] && nums[i] == nums[i - 1])) continue;
            visited[i] = true;
            tmp.add(nums[i]);
            permutation(nums, res, tmp, visited);
            tmp.remove(tmp.size() - 1);
            visited[i] = false;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值