Leetcode78——Subsets

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

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));
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,768评论 0 33
  • LeetCode 刷题随手记 - 第一部分 前 256 题(非会员),仅算法题,的吐槽 https://leetc...
    蕾娜漢默阅读 17,909评论 2 36
  • 326. Power of Three Given an integer, write a function to...
    跑者小越阅读 2,156评论 0 1
  • Description: Given a set of distinct integers, return all...
    黑山老水阅读 239评论 0 0
  • 每天,尤其是早晨六点之前,总感觉这段时间很神秘,鸟开始叫,天空开始泛白,黑夜褪去,万物从沉寂中复苏,也有一些开始沉...
    磁暴魔王特斯拉阅读 262评论 0 2