LeetCode每日一题:子集 1

问题描述

Given a set of distinct integers, S, return all possible subsets.
Note:
Elements in a subset must be in non-descending order.
The solution set must not contain duplicate subsets.

For example,
If S =[1,2,3], a solution is:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]

问题分析

这题让我们求S所有可能的子集,并且子集的排列不能为递减的,所以我们在算之前进行一次排序操作。采用DFS搜索找所有的子集

代码实现

 public ArrayList> subsets(int[] S) {
        ArrayList> result = new ArrayList<>();
        if (S.length == 0) return result;
        ArrayList list = new ArrayList<>();
        Arrays.sort(S);
        dfsSubsets(S, 0, list, result);
        return result;
    }

    private void dfsSubsets(int[] num, int start, ArrayList list, ArrayList> result) {
        result.add(new ArrayList(list));
        for (int i = start; i < num.length; i++) {
            list.add(num[i]);
            dfsSubsets(num, i + 1, list, result);
            list.remove(list.size() - 1);
        }
    }

你可能感兴趣的:(LeetCode每日一题:子集 1)