LeetCode0078.子集

本文深入探讨了子集生成算法的实现,通过递归方法和栈结构,详细讲解了如何生成给定数组的所有可能子集,确保解集不包含重复子集。提供了具体的代码示例,包括状态维护和递归调用的细节。

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

78.子集

描述

给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。

**说明:**解集不能包含重复的子集。

实例

输入: nums = [1,2,3]
输出:
[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

题解

全排列问题

  • 维护一个栈用于保存迭代时的状态
  • 栈中使用int[]描述一个状态
  • 递归调用
  • 其中,index表示当前考虑哪一个位置元素的不同情况
  • 其中,结尾处的state.pop()用于保证当前状态被移除
public static List<List<Integer>> subsets(int[] nums) {
    List<List<Integer>> linkedLists = new LinkedList<>();

    getAllPoss(nums,0,new Stack<int[]>(),linkedLists);

    return linkedLists;
}

public static void getAllPoss(int[] nums, int index,Stack<int[]> state, List<List<Integer>> linkedLists){
    int[] nowState;
    int[] lastState;

    if (index == nums.length){
        //添加结果到LinkedLists
        lastState = state.pop();
        List<Integer> nowList = new LinkedList<>();
        for (int i = 0; i < lastState.length; i++) {
            if (lastState[i] == 1)
                nowList.add(nums[i]);
        }
        linkedLists.add(nowList);
        return;
    }



    if (state.empty()){
        nowState = new int[nums.length];
    } else {
        lastState = state.pop();
        state.push(lastState);
        nowState = lastState.clone();
    }

    nowState[index] = 1;
    state.push(nowState);
    getAllPoss(nums,index+1,state,linkedLists);

    nowState[index] = -1;
    state.push(nowState);
    getAllPoss(nums,index+1,state,linkedLists);

    if (!state.empty())
        state.pop();


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值