47. Permutations II

本文深入探讨了在可能包含重复元素的数组中寻找所有唯一排列的算法实现。通过排序和递归方法,确保生成的排列结果不包含重复项。文章详细介绍了算法的步骤,包括如何在每次交换元素后恢复数组部分排序,以准备下一次去重。

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

难度:medium

题目:给定一组可能包含重复数的集合,返回所有可能的排列。

思路:先对数组进行排序,为去重做准备。然后借助递归遍历所有数。重点在于,当每次选定一个数做完交换之后,恢复时要对两个交换数及之间的所有数做排序。继续为接下来的去重做准备。

class Solution {
    public List<List<Integer>> permuteUnique(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> result = new ArrayList<>();
        permuteUnique(nums, 0, new Stack<Integer>(), result);
        
        return result;
    }
    
    private void permuteUnique(int[] nums, int idx, Stack<Integer> stack, List<List<Integer>> result) {
        if (idx == nums.length) {
            result.add(new ArrayList<>(stack));
            return;
        }
        
        for (int i = idx; i < nums.length; i++) {
            if (idx == i || nums[i] != nums[i - 1]) {
                stack.push(nums[i]);
                swap(nums, idx, i);
                permuteUnique(nums, idx + 1, stack, result);
                swap(nums, i, idx);
                Arrays.sort(nums, idx, i + 1);
                stack.pop();
            }
        }
    }

    private void swap(int[] nums, int i, int j) {
        int t = nums[i];
        nums[i] = nums[j];
        nums[j] = t;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值