133 - 47 全排列2

题目

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

示例:

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

解答

https://leetcode-cn.com/problems/permutations-ii/solution/hui-su-jian-zhi-deng-jie-ji-chu-quan-pai-lie-by-ge/

const helper = function(nums, level, res) {
  if (level === nums.length) {
    res.push([...nums])
    return
  }
  const map = new Map()
  for (let i = level; i < nums.length; i++) {
    if (!map.get(nums[i])) {
      map.set(nums[i], true);
      [nums[i], nums[level]] = [nums[level], nums[i]]
      helper(nums, level + 1, res);
      [nums[i], nums[level]] = [nums[level], nums[
        i]]
    }
  }
}
var permuteUnique = function(nums) {
  if (nums.length === 0) {
    return []
  } else if (nums.length === 1) {
    return [
      [nums[0]]
    ]
  }
  nums.sort((a, b) => a - b)
  const res = []
  helper(nums, 0, res)
  return res
};

Runtime: 72 ms, faster than 86.35% of JavaScript online submissions for Permutations II.

Memory Usage: 37.8 MB, less than 22.22% of JavaScript online submissions for Permutations II.

https://leetcode-cn.com/problems/permutations-ii/solution/hui-su-suan-fa-python-dai-ma-java-dai-ma-by-liwe-2/

Runtime: 56 ms, faster than 97.36% of Python3 online submissions for Permutations II.

Memory Usage: 12.7 MB, less than 100.00% of Python3 online submissions for Permutations II.

把函数放在里面,就可以少传一些参数了。

Runtime: 56 ms, faster than 97.36% of Python3 online submissions for Permutations II.

Memory Usage: 13.1 MB, less than 95.56% of Python3 online submissions for Permutations II.

Runtime: 8 ms, faster than 95.61% of Go online submissions for Permutations II.

Memory Usage: 7.9 MB, less than 50.00% of Go online submissions for Permutations II.

Last updated

Was this helpful?