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
|
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; };
|