Voyz's Studio.

LeetCode算法笔记--子集

字数统计: 165阅读时长: 1 min
2020/12/19 Share

LeetCode算法笔记–Day46

题目1:

78. Subsets

Given a set of distinct integers, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

example
input: nums = [1,2,3]

output: [
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]

回溯算法

Analyse:

  • 回溯算法基本结构
1
2
3
4
5
6
7
8
9
10
result = []
def backtrack(路径, 选择条件):
if 满足结束条件:
result.add(路径)
return

for 选择 in 选择条件:
做选择
backtrack(路径, 新的选择条件)
撤销选择

My Answer:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* @param {number[]} nums
* @return {number[][]}
*/
var subsets = function(nums) {
let res = [];

let trackBack = function(start,track){
res.push(track);
for(let i=start;i<nums.length;i++){
track.push(nums[i]);
trackBack(i+1,track.slice());
track.pop();
}
}

trackBack(0,[]);
return res;
};
CATALOG
  1. 1. LeetCode算法笔记–Day46
    1. 1.1. 题目1:
      1. 1.1.1. 78. Subsets
      2. 1.1.2. 回溯算法
      3. 1.1.3. Analyse:
      4. 1.1.4. My Answer: