0047. Permutations II (M)

Permutations II (M)

题目

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

题意

求给定数组的全排列,注意数组中有重复元素。

思路

46. Permutations 相比,多了重复元素,只要在46解法基础上加上相应的限制即可。

  1. 回溯法:
    • 使用hash:用一张hash表记录整个搜索中对应下标的数是否已被使用,每一层递归中再用一张hash表记录当前递归层次中已经插入过(又移除)的数字,每次操作都往已有序列后插入一个未被使用的数(既是整个搜索中未被使用,也是当前递归中未被使用),更新hash,递归,再移除改数,更新hash。
    • 不使用hash:对于结果序列中的每一个位置index,它可能存放的数为nums从index到最后一个位置nums.length-1中的任意一个数,但要保证每次存放的都是不同的数。所以每次操作都从这(nums.length - index)个数中选出一个,并判断该数是否已经存放过,若没有则放到当前空位,再对右边的空位进行递归操作。
  2. 结合 31. Next Permutation 来实现全排列。

代码实现

Java

回溯法无hash

class Solution {
    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> ans = new ArrayList<>();
        permute(nums, 0, ans);
        return ans;
    }

    private void permute(int[] nums, int index, List<List<Integer>> ans) {
        if (index == nums.length - 1) {
            List<Integer> list = new ArrayList<>();
            for (int i = 0; i < nums.length; i++) {
                list.add(nums[i]);
            }
            ans.add(list);
            return;
        }

        for (int i = index; i < nums.length; i++) {
            // 每次都要判断该数是否已经使用过
            boolean flag = false;
            for (int j = index; j < i; j++) {
                if (nums[i] == nums[j]) {
                    flag = true;
                    break;
                }
            }
            if (flag) {
                continue;
            }

            swap(nums, index, i);
            permute(nums, index + 1, ans);
            swap(nums, index, i);
        }
    }

    private void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}

回溯法hash

class Solution {
    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> ans = new ArrayList<>();
        permute(nums, new boolean[nums.length], new ArrayList<>(), ans);
        return ans;
    }

    private void permute(int[] nums, boolean[] hash, List<Integer> list, List<List<Integer>> ans) {
        if (list.size() == nums.length) {
            ans.add(new ArrayList<>(list));
        }

        // 当前递归中也要用一张hash表记录已经插入过的数字
        Set<Integer> used = new HashSet<>();
        for (int i = 0; i < nums.length; i++) {
            if (!hash[i] && !used.contains(nums[i])) {
                used.add(nums[i]);
                list.add(nums[i]);
                hash[i] = true;
                permute(nums, hash, list, ans);
                hash[i] = false;
                list.remove(list.size() - 1);
            }
        }
    }
}

nextPermutation

class Solution {
    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> ans = new ArrayList<>();
        Arrays.sort(nums);
        while (true) {
            List<Integer> list = new ArrayList<>();
            for (int i = 0; i < nums.length; i++) {
                list.add(nums[i]);
            }
            ans.add(list);
            if (hasNextPermutation(nums)) {
                nextPermutation(nums);
            } else {
                break;
            }
        }
        return ans;
    }

    // 根据当前排列计算下一个排列 
    private void nextPermutation(int[] nums) {
        int i = nums.length - 2;
        while (i >= 0 && nums[i] >= nums[i + 1]) {
            i--;
        }
        int j = nums.length - 1;
        while (nums[j] <= nums[i]) {
            j--;
        }
        swap(nums, i, j);
        reverse(nums, i + 1, nums.length - 1);
    }

    // 判断是否存在下一个排列,即判断是否已经是完全逆序数列
    private boolean hasNextPermutation(int[] nums) {
        int i = nums.length - 2;
        while (i >= 0 && nums[i] >= nums[i + 1]) {
            i--;
        }
        return i >= 0;
    }

    private void reverse(int[] nums, int left, int right) {
        while (left < right) {
            swap(nums, left++, right--);
        }
    }

    private void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}

JavaScript

回溯法无hash

/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var permuteUnique = function (nums) {
  let lists = []
  dfs(nums, 0, lists)
  return lists
}


let dfs = function (nums, index, lists) {
  if (index === nums.length) {
    lists.push([...nums])
    return
  }

  let used = new Set()
  for (let i = index; i < nums.length; i++) {
    if (!used.has(nums[i])) {
      used.add(nums[i]);
      [nums[index], nums[i]] = [nums[i], nums[index]]
      dfs(nums, index + 1, lists);
      [nums[index], nums[i]] = [nums[i], nums[index]]
    }
  }
}

回溯法hash

/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var permuteUnique = function (nums) {
  let lists = []
  dfs(nums, 0, [], lists, new Set())
  return lists
}

let dfs = function (nums, index, list, lists, record) {
  if (index === nums.length) {
    lists.push([...list])
    return
  }

  let used = new Set()
  for (let i = 0; i < nums.length; i++) {
    if (!record.has(i) && !used.has(nums[i])) {
      used.add(nums[i])
      record.add(i)
      list.push(nums[i])
      dfs(nums, index + 1, list, lists, record)
      list.pop()
      record.delete(i)
    }
  }
}

猜你喜欢

转载自www.cnblogs.com/mapoos/p/13211463.html