Skip to content

Latest commit

 

History

History
44 lines (35 loc) · 846 Bytes

回溯-78. 子集.md

File metadata and controls

44 lines (35 loc) · 846 Bytes

78. 子集

LeetCode | 78. 子集 | 中等

给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。

解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。

示例 1:

输入:nums = [1,2,3]
输出:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]

示例 2:

输入:nums = [0]
输出:[[],[0]]

回溯

/**
 * 回溯
 * 时间复杂度:O(2^n)
 * 空间复杂度:O(n×2^n)
 */
var subsets = function (nums) {
  const res = [[]]
  if (!nums.length) return res
  function dps(arr, index) {
    if (index >= nums.length) return
    const temp = [...arr, nums[index]]
    res.push(temp)
    dps(temp, index + 1)
    dps(arr, index + 1)
  }
  dps([], 0)
  return res
}