Skip to main content

🟡 剑指 Offer II 084. 含有重复元素集合的全排列

LeetCode 提示

题目难度 中等

原题链接 🔗 leetcode

题解1#

注意去重

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