前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode 题目解析之 Subsets

Leetcode 题目解析之 Subsets

原创
作者头像
ruochen
发布2022-01-10 20:09:36
1.2K0
发布2022-01-10 20:09:36
举报

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,

[]

]

代码语言:txt
复制
    int target;// 次数
    Integer[] stack;// 存储每次排列
    List<List<Integer>> rt;// 存储结果
    public void search(int p, int[] nums) {
        // 若长度为k,则stack是其中一个结果,保存结果
        if (p == target) {
            rt.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);
        rt = 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 rt;
    }

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
http://www.vxiaotou.com