LeetCode 106 Permutations II

本文介绍了一种算法,用于生成包含重复数字的数组的所有唯一排列。通过递归深度优先搜索实现,加入了一个有效性检查来避免重复生成相同的排列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

分析:

这和Permutations的方法是一样的,不同的地方就是加了一个判断,判断当前元素是否已经当过头元素,即从start开始到curr如果有

和curr相等的元素,说明curr已经当过头元素,不能再交换了。

public class Solution {
    public List<List<Integer>> permuteUnique(int[] num) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        if(num==null || num.length==0)
            return res;
        dfs(res, num, 0);
        return res;
    }
    private void dfs(List<List<Integer>> res, int[] num, int start){
        if(start == num.length){
            res.add(arrayToList(num));
            return;
        }
        for(int i=start; i<num.length; i++){
            //不同之处就是这里加了一个判断
            if(isValid(num, start, i)){
                swap(num, start, i);
                dfs(res, num, start+1);
                swap(num, start, i);
            }
        }
    }
    private List<Integer> arrayToList(int[] num){
        List<Integer> list = new ArrayList<Integer>();
        for(int i=0; i<num.length; i++)
            list.add(num[i]);
        return list;
    }
    private boolean isValid(int[] num, int start, int curr){
        //如果curr之前有和curr一样的元素,说明curr已经背移动到前面过了
        for(int i=start; i<curr; i++){
            if(num[i] == num[curr])
                return false;
        }
        return true;
    }
    private void swap(int[] num, int index1, int index2){
        int temp = num[index1];
        num[index1] = num[index2];
        num[index2] = temp;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值