【Leetcode】Subsets

来源:互联网 发布:mac装microsoft office 编辑:程序博客网 时间:2024/06/16 14:13

题目链接:https://leetcode.com/problems/subsets/

题目:

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

思路:

子集问题。本题求的是所有子集,在Combinations 题目中,我们实现了指定大小的子集,稍微改变一下就好了。还要注意一下,题目要求子集是非单减排序的,所以集合初始时候要排序一遍。

算法:

List<List<Integer>> iLists = new ArrayList<List<Integer>>();List<Integer> list = new ArrayList<Integer>();int cl[] = null;public List<List<Integer>> subsets(int[] nums) {this.cl = nums;Arrays.sort(nums);dspSubSets(0);return iLists;}void dspSubSets(int cur) {iLists.add(new ArrayList<Integer>(list));for (int i = cur; i < cl.length; i++) {list.add(cl[i]);dspSubSets(i + 1);list.remove(list.size() - 1);}}


0 0
原创粉丝点击