给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
说明:解集不能包含重复的子集。
示例:
输入: nums = [1,2,3]输出:[[3],[1],[2],[1,2,3],[1,3],[2,3],[1,2],[]]
参考思路:
使用回溯算法,对于每个点,存在两种可能,选它或者不选它,对这种选择依次递归,收集结果集
/**
* @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;
};
