Leetcode78——Subsets

本文介绍了一种使用递归法生成给定整数数组所有可能子集的方法。通过选择或跳过数组中的每个元素来构建子集,确保结果中不包含重复的子集。提供了完整的Java代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

文章作者:Tyan
博客:noahsnail.com  |  优快云  |  简书

1. 问题描述

Given a set of distinct integers, nums, return all possible subsets.

Note: The solution set must not contain duplicate subsets.

For example,
If nums = [1,2,3], a solution is:

[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

2. 求解

递归法

这道题类似于数组的组合问题,可以用递归法求解。N个数中每个数都分为要与不要两种情况,求解的过程如下图。递归的边界条件为N个数都遍历完了。

递归过程

public class Solution {
    public static List<List<Integer>> result = new ArrayList<List<Integer>>();
    public List<List<Integer>> subsets(int[] nums) {
        result.clear();
        result.add(new ArrayList<Integer>());
        combination(nums, 0, new ArrayList<Integer>());
        return result;
    }

    public void combination(int[] nums, int index, List<Integer> list) {
        if(index == nums.length) {
            return;
        }
        combination(nums, index + 1, new ArrayList<Integer>(list));
        list.add(nums[index]);
        result.add(list);
        combination(nums, index + 1, new ArrayList<Integer>(list));
    }
}
### LeetCode78题 子集 的Python实现 LeetCode78题的目标是从给定整数集合 `nums` 中找到所有的可能子集。此问题可以通过回溯算法解决,类似于组合问题中的方法[^4]。 以下是基于回溯法的解决方案: ```python class Solution: def subsets(self, nums: list[int]) -> list[list[int]]: result = [] def backtrack(start_index, current_subset): # 将当前子集加入到结果集中 result.append(current_subset.copy()) # 遍历剩余元素并尝试将其加入子集 for i in range(start_index, len(nums)): current_subset.append(nums[i]) backtrack(i + 1, current_subset) current_subset.pop() backtrack(0, []) return result ``` #### 解决方案说明 上述代码通过递归的方式构建所有可能的子集。每次调用函数时都会将当前状态下的子集保存至最终的结果列表中。随后继续探索下一个可选元素,并在完成一次分支后撤销最后的选择以便返回上一层进行其他可能性的探索。 这种方法的时间复杂度为 \(O(2^n)\),其中 \(n\) 是输入数组的大小。这是因为对于每一个元素都有两种选择——要么包含它,要么不包含它,从而形成指数级的增长关系。 #### 示例运行 假设我们有以下输入数据: ```python solution = Solution() print(solution.subsets([1, 2, 3])) ``` 输出将是: ```plaintext [[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]] ``` 这表示了 `[1, 2, 3]` 所有可能形成的子集。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值