题目描述:给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
说明:解集不能包含重复的子集。
示例: 输入: nums = [1,2,3]\
输出:\
[\
[3],\
[1],\
[2],\
[1,2,3],\
[1,3],\
[2,3],\
[1,2],\
[]\
]
1.有思路,图解,可行 2.找到循环逻辑和边界条件 3.写代码
什么时候用
看两个特征:
- 题目中暗示了一个或多个解,并且要求我们详尽地列举出每一个解的内容时,一定要想到 DFS、想到递归回溯。
- 题目经分析后,可以转化为树形逻辑模型求解。
怎么用
一个模型——树形逻辑模型;两个要点——递归式和递归边界。
function fun(arr) {
const len = arr.length
const res = []
const resFinally = []
const dfs = (floor) => {
if (floor === len) {
resFinally.push(res.slice())
return;
}
res.push(arr[floor])
dfs(floor + 1)
res.pop()
dfs(floor + 1)
}
dfs(0)
console.log(resFinally)
}
// 剪枝
function fun(arr) {
const len = arr.length
const res = []
const resFinally = []
const dfs = (floor) => {
if (res.length === 2) {
resFinally.push(res.slice())
return;
}
if (floor === len) {
return;
}
res.push(arr[floor])
dfs(floor + 1)
res.pop()
dfs(floor + 1)
}
dfs(0)
console.log(resFinally)
}
fun([1, 2, 3, 4])