78. Subsets (M)

本文深入探讨了求解数组幂集(所有可能的子集)的两种算法:回溯法和位运算法。通过实例说明了如何使用这两种方法求得一个整数数组的所有子集,包括详细的代码实现。

Subsets (M)

Given a set of distinct integers, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Example:

Input: nums = [1,2,3]
Output:
[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

题意

求一个数组的幂集(即所有子集,包括全集和空集,构成的集族)。

思路

回溯法。

也可以利用位运算来求子集,具体方法参考 LeetCode 78. Subsets (位运算入门:利用位运算求子集)


代码实现 - 回溯法

class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> ans = new ArrayList<>();
        subsets(nums, 0, new ArrayList<>(), ans);   
        return ans;
    }

    private void subsets(int[] nums, int index, List<Integer> list, List<List<Integer>> ans) {
        if (index == nums.length) {
            ans.add(new ArrayList<>(list));
            return;
        }

        subsets(nums, index + 1, list, ans);
        list.add(nums[index]);
        subsets(nums, index + 1, list, ans);
        list.remove(list.size() - 1);
    }
}

代码实现 - 位运算

class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> ans = new ArrayList<>();
        List<Integer> list = new ArrayList<>();
        int all = 1 << (nums.length);		// 总情况数
        for (int i = 0; i < all; i++) {
            // 判断数组中每一个数是否应该添加
            for (int j = 0; j < nums.length; j++) {
                if ((i & (1 << j)) > 0) {
                    list.add(nums[j]);
                }
            }
            ans.add(new ArrayList<>(list));
            list.clear();
        }
        return ans;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值