78.Subsets

Given an integer array nums, return all possible subsets (the power set). The solution set must not contain duplicate subsets.

Example 1:

Input: nums = [1,2,3]
Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]

Example 2:

Input: nums = [0]
Output: [[],[0]]

Constraints:

  • 1 <= nums.length <= 10
  • -10 <= numsi <= 10

Analyze

由题意可知该题是组合问题, 可以使用回溯法解决。

/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var subsets = function (nums) {
  const list = []
  const tmpList = []

  backTrack(list, tmpList, nums, 0)

  return list
};

function backTrack(list, tmpList, nums, start) {
  list.push(tmpList.slice())

  for (let i = start; i < nums.length; i++) {
    tmpList.push(nums[i])
    backTrack(list, tmpList, nums, i + 1)
    tmpList.splice(tmpList.length - 1, 1)
  }
}