【力扣-中等】47. 全排列 II

给定一个可包含重复数字的序列,返回所有不重复的全排列。

示例:输入: [1,1,2]
输出:
[
  [1,1,2],
  [1,2,1],
  [2,1,1]
]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/permutations-ii

【回溯】

boolean[] fill;

    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> ans = new ArrayList<List<Integer>>();
        List<Integer> res = new ArrayList<Integer>();
        fill = new boolean[nums.length];
        Arrays.sort(nums);
        backtrack(nums, ans, 0, res);
        return ans;
    }

    public void backtrack(int[] nums, List<List<Integer>> ans, int index, List<Integer> res) {
        if (index == nums.length) {
            ans.add(new ArrayList<>(res));
            return;
        }
        for (int i = 0; i < nums.length; ++i) {
            if (fill[i] || (i > 0 && nums[i] == nums[i - 1] && !fill[i - 1])) {
                continue;
            }
            res.add(nums[i]);
            fill[i] = true;
            backtrack(nums, ans, index + 1, res);
            fill[i] = false;
            res.remove(index);
        }
    }

 


版权声明:本文为qq_39380838原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。