子集-中等


难度:中等

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

示例:

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


解题思路:
![image.png](https://cdn.nlark.com/yuque/0/2020/png/218767/1590039763805-1043d84c-929d-4033-bce9-9bd8bf3d6e7c.png#align=left&display=inline&height=193&margin=%5Bobject%20Object%5D&name=image.png&originHeight=386&originWidth=1428&size=137831&status=done&style=none&width=714) ```javascript var subsets = function(nums) { let ws = [[]]; for(let i=0; i < nums.length; ++i) { for(let j=0, len = ws.length; j < len; ++j) { ws.push(ws[j].concat([nums[i]])); } } return ws; }; ```


回朔算法

var subsets = function (nums) {
  let ans = [];
  let path = [];
  dfs(ans, path, 0, nums);
  return ans;
};
const dfs = function (ans, path, start, nums) {
  if (path.length > nums.length) return;
  ans.push(path);
  for (let i = start; i < nums.length; i++) {
    path.push(nums[i]);
    dfs(ans, path.slice(), i + 1, nums);
    path.pop();
  }
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
最后更新时间: 5/21/2020, 9:35:29 PM