47. Permutations II

有重复数字的排列,难点在去重判断。首先需要对数组进行排序,然后设置一个和原数组等长的boolean数组,判断两种情况下是否需要跳过重复数字,1.本数字是否被用过 2.如果和前面的数字相等,但是它没有被用过,就直接跳过当前数字,因为这种可能性已经被添加过。

public List<List<Integer>> permuteUnique(int[] nums) {
    List<List<Integer>> res = new ArrayList<>();
    List<Integer> path = new ArrayList<>();
    boolean[] used = new boolean[nums.length];
    Arrays.sort(nums);
    dfs(nums, path, res, used);
    return res;
}

public void dfs(int[] nums, List<Integer> path, List<List<Integer>> res, boolean[] used) {
    if (path.size() == nums.length) {
        res.add(new ArrayList<>(path));
        return;
    }
    for (int i = 0; i < nums.length; i++) {
        if (used[i]) continue; // if this num has used before, do not use it again
        if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) continue;
        // if two nums are the same, and the previous one were not used, then do not use this num
        used[i] = true;
        path.add(nums[i]);
        dfs(nums, path, res, used);
        used[i] = false;
        path.remove(path.size() - 1);
    }
}

results matching ""

    No results matching ""