力扣算法ing(61 / 100)
4.20 78.子集
给你一个整数数组 nums
,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。
解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。
示例 1:
输入:nums = [1,2,3]
输出:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
示例 2:
输入:nums = [0]
输出:[[],[0]]
提示:
1 <= nums.length <= 10
-10 <= nums[i] <= 10
nums
中的所有元素 互不相同
我的思路:
子集:不能包含重复的子集
类似于回文数切割叭
for循环循环的是字符长度
当startIndex === 字符长度的时候才结束
我的代码:
function subsets(nums: number[]): number[][] {const path = [];const res = [];res.push([]);function backTraking(startIndex : number){if(startIndex === nums.length - 1){res.push([...path]);}for(let i = startIndex ; i < nums.length ;i++){path.push(nums.toString().substring(startIndex , i+1));backTraking( i + 1);path.pop();}}backTraking(0);return res;};
执行出错!
nums.toString().substring(startIndex , i+1)
,这会将数字转换成字符串并截取子字符串,这不是生成子集的正确方法。应该直接将数字添加到path当中。
终止条件 if(startIndex === nums.length - 1)
也不正确。这个条件会导致函数在到达最后一个元素时才添加子集,而不是在每一步都添加。
解决方案:
每次循环就添加数字到path当中,每次也将path添加到res当中,当startIndex===nums.length才结束,避免在遍历最后一个数字就停止的情况。
我的代码:
function subsets(nums: number[]): number[][] {const path = [];const res = [];res.push([]);function backTraking(startIndex : number){if(startIndex === nums.length){return;}for(let i = startIndex ; i < nums.length ;i++){path.push(nums[i]);res.push([...path]);backTraking( i + 1);path.pop();}}backTraking(0);return res;};
总结:这一道题目在经过前两题的熏陶之后,已经有了思路了,但是不能够照搬回溯的公式在这题目也得到了验证。我最开始就是按照回溯的公式写的,执行错误,这个不是直接截取子集了,应该是没遍历一个就添加到path中,把path添加到res中。