Skip to content
本页目录

全排列篇

元素无重不可复选

剑指 Offer II 083. 没有重复元素集合的全排列

回溯

JavaScript
const permute = nums => {
  const [ret, len] = [[], nums.length]
  const used = Array(len)
  const dfs = (path = []) => {
    if (path.length === len) {
      ret.push([...path])
      return
    }
    for (let i = 0; i < len; i++) {
      if (used[i]) continue
      path.push(nums[i])
      used[i] = true
      dfs(path)
      path.pop()
      used[i] = false
    }
  }
  dfs()
  return ret
}

时间复杂度:O(n*n!);空间复杂度:O(n)

元素有重不可复选

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

回溯

对原数据原地排序后,跳过重复元素即可!

JavaScript
const permuteUnique = nums => {
  const [ret, len] = [[], nums.length]
  const used = Array(len)
  nums.sort((a, b) => a - b)
  const dfs = (path = []) => {
    if (path.length === len) {
      ret.push([...path])
      return
    }
    for (let i = 0; i < len; i++) {
      if (used[i]) continue
      // 剪枝:!used[i - 1] 确保相同元素在排列中的相对位置保持不变
      if (i > 0 && nums[i] === nums[i - 1] && !used[i - 1]) continue
      path.push(nums[i])
      used[i] = true
      dfs(path)
      path.pop()
      used[i] = false
    }
  }
  dfs()
  return ret
}

时间复杂度:O(n*n!);空间复杂度:O(n)