78. Subsets

本文解析了LeetCode中子集问题的实现方法,通过递归算法生成所有可能的子集,并确保结果集中没有重复子集。提供了详细的Java代码示例及解释,包括递归的三要素,并对比了几种不同的解决方案。

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

题目:

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],
  []
]

链接:https://leetcode.com/problems/subsets/#/description

4/22/2017

算法班

提到了递归的三要素?

 1 public class Solution {
 2     public List<List<Integer>> subsets(int[] nums) {
 3         List<List<Integer>> ret = new ArrayList<>();
 4 
 5         if (nums == null) {
 6             return ret;
 7         }
 8         
 9         Arrays.sort(nums);
10         
11         helper(ret, new ArrayList<Integer>(), nums, 0);
12         
13         return ret;
14     }
15     
16     private void helper(List<List<Integer>> ret,
17                         ArrayList<Integer> subset,
18                         int[] nums,
19                         int startIndex) {
20         // return condition is implicit here, since subset ends when reach to last element of nums
21         ret.add(new ArrayList<Integer>(subset));
22         for (int i = startIndex; i < nums.length; i++) {
23             subset.add(nums[i]);
24             helper(ret, subset, nums, i + 1);
25             subset.remove(subset.size() - 1);
26         }
27     }    
28 }

有人的总结:

https://discuss.leetcode.com/topic/46159/a-general-approach-to-backtracking-questions-in-java-subsets-permutations-combination-sum-palindrome-partitioning

python大哥的几种方法,包括reduce(), itertools.combinations()

https://discuss.leetcode.com/topic/15819/short-and-clear-solutions

有iterative方法的,但是不如普通方法个人感觉

https://discuss.leetcode.com/topic/19110/c-recursive-iterative-bit-manipulation-solutions-with-explanations

更多讨论:

https://discuss.leetcode.com/category/86/subsets

转载于:https://www.cnblogs.com/panini/p/6751395.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值