给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
说明:解集不能包含重复的子集。
示例:

  1. 输入: nums = [1,2,3]
  2. 输出:
  3. [
  4. [3],
  5. [1],
  6. [2],
  7. [1,2,3],
  8. [1,3],
  9. [2,3],
  10. [1,2],
  11. []
  12. ]

参考思路:

使用回溯算法,对于每个点,存在两种可能,选它或者不选它,对这种选择依次递归,收集结果集
image.png

/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var subsets = function(nums) {
    const res = [];
    const dfs = (index, path) => {
        if (index === nums.length) {
            res.push([...path]);
            return;
        }
        path.push(nums[index]);
        dfs(index + 1, path);
        path.pop();
        dfs(index + 1, path);
    }

    dfs(0, []);

    return res;
};