LeetCode 78. Subsets

问题描述

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

问题分析

  • 给定一个不含重复元素的数组,找出它的全部子集(子序列)
  • 有以下两种思路:
    • 每一个位置上的元素存在要或者不要的关系,要或者不要便是当前的两种决策
      这里写图片描述
    • 类似于寻找组合的过程中,不断向结果集中添加中间路径
      这里写图片描述

代码实现

  • 方法1:
    public List<List<Integer>> subsets(int[] nums) {
        if (nums == null || nums.length == 0) {
            return new ArrayList<>();
        }
        List<List<Integer>> res = new ArrayList<>();
        findSubsets(nums, 0, new ArrayList<>(), res);
        return res;
    }
    public void findSubsets(int[] nums, int i, ArrayList<Integer> path, List<List<Integer>> res) {
        if (i == nums.length) {
            res.add(new ArrayList<>(path));
            return;
        }
        //不要i位置元素
        findSubsets(nums, i + 1, path, res);
        //要i位置元素
        path.add(nums[i]);
        findSubsets(nums, i + 1, path, res);
        //回溯
        path.remove(path.size() - 1);
        return;
    }
  • 方法2:
    public List<List<Integer>> subsets(int[] nums) {
        if (nums == null || nums.length == 0) {
            return new ArrayList<>();
        }
        List<List<Integer>> res = new ArrayList<>();
        findSubsets(nums, 0, new ArrayList<>(), res);
        return res;
    }

    public void findSubsets(int[] nums, int i, ArrayList<Integer> path, List<List<Integer>> res) {

        if (i == nums.length) {
            res.add(new ArrayList<>(path));
            return;
        }
        res.add(new ArrayList<>(path));
        for (int j = i; j < nums.length; ++j) {
            path.add(nums[j]);
            findSubsets(nums, j + 1, path, res);
            path.remove(path.size() - 1);
        }
        return;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值