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

和一般的Permutation不一样的是,这种permutation需要排序,使相同的元素能够相邻,选取下一个元素的时候,要查看这个元素的前一个元素是否和它相同,如果相同而且没有使用过,就不用选取这个元素,因为如果选取了这个元素,所得的结果被包含于选取了前一个相同元素的结果中。
代码如下:
public class Solution {
    int length;
    public List<List<Integer>> permuteUnique(int[] nums) {
        length = nums.length;
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        if (length == 0) {
            return result;
        }
        Arrays.sort(nums);
        boolean[] flags = new boolean[length];
        Arrays.fill(flags, false);
        List<Integer> candidate = new ArrayList<Integer>();
        helper(nums, length, flags, result, candidate);
        return result;
    }
    private void helper(int[] nums, int n, boolean[] flags, List<List<Integer>> result, List<Integer> candidate) {
        if (n == 0) {
            result.add(new ArrayList<Integer>(candidate));
        }
        int ll = candidate.size();
        for (int i = 0; i < length; i++) {
            if (!flags[i]) {
                //if the number appears more than once and the same number before it has not been used
                if (i != 0 && nums[i] == nums[i - 1] && !flags[i - 1]) {
                    continue;
                }
                flags[i] = true;
                candidate.add(nums[i]);
                helper(nums, n - 1, flags, result, candidate);
                candidate.remove(ll);
                flags[i] = false;
            }
        }
    }
}

 

转载于:https://www.cnblogs.com/Gryffin/p/6228500.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值