LeetCode 078 Subsets

来源:互联网 发布:pingfang sc for mac 编辑:程序博客网 时间:2024/06/17 22:01

题目描述

Given a set of distinct integers, nums, 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 nums =“[1,2,3]” , a solution is:

[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]

分析

参考 LeetCode 076 Combinations,只是分别求出0~nums.length长度的结果集。
本题只适用于数组元素没有重复的情况,首先对其排序。

代码

    int target;// 次数    Integer[] stack;// 存储每次排列    List<List<Integer>> result;// 存储结果    public void search(int p, int[] nums) {        // 若长度为k,则stack是其中一个结果,保存结果        if (p == target) {            result.add(new ArrayList<Integer>(Arrays.asList(stack)));            return;        }        for (int i = 0; i < nums.length; i++) {            if (p > 0 && nums[i] <= stack[p - 1]) {                continue;            }            stack[p] = nums[i];            search(p + 1, nums);        }    }    public List<List<Integer>> subsets(int[] nums) {        Arrays.sort(nums);        result = new ArrayList<List<Integer>>();        // 分别做0~num.length长度的组合        for (int i = 0; i <= nums.length; i++) {            target = i;            stack = new Integer[i];            search(0, nums);        }        return result;    }
0 0