剑指 Offer II 079. 所有子集(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 中的所有元素 互不相同
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/subsets
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
分析
参考:https://github.com/youngyangyang04/leetcode-master/blob/master/problems/0078.%E5%AD%90%E9%9B%86.md
剑指offer做法:
https://blog.csdn.net/weixin_43942435/article/details/123323821
题解(Java)
三部曲法:
class Solution {
List<List<Integer>> ans = new LinkedList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> subsets(int[] nums) {
backTracking(nums, 0);
return ans;
}
private void backTracking(int[] nums, int start) {
ans.add(new ArrayList<Integer>(path));
for (int i = start; i < nums.length; i++) {
path.add(nums[i]);
backTracking(nums, i + 1);
path.removeLast();
}
}
}
选/不选法:
class Solution {
List<List<Integer>> ans = new LinkedList<>();
public List<List<Integer>> subsets(int[] nums) {
helper(0, new LinkedList<Integer>(), nums);
return ans;
}
private void helper(int start, List<Integer> list, int[] nums) {
if (start == nums.length) {
ans.add(new LinkedList<Integer>(list));
} else {
helper(start + 1, list, nums);//不选
list.add(nums[start]);//选
helper(start + 1, list, nums);//判断下一个数
list.remove(list.size() - 1);//回溯
}
}
}