【LeetCode OJ 078】Subsets

来源:互联网 发布:排序算法时间复杂度 编辑:程序博客网 时间:2024/06/07 00:01

题目链接: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],  []]
解题思路:搜了一下网上的解题思路,有一个感觉很巧妙。大致的思路是这样的,一个数组的子集个数是这个数组的长度的n次方(2^n),例如a[2]={1,2},子集个数就是2^2=4,二进制表示为00,01,10,11,分别表示空集、{1}、{2}、{12},具体的实现代码如下:

public class Solution{public List<List<Integer>> subsetsWithDup(int[] nums) {List<List<Integer>> result=new ArrayList<List<Integer>>();//先对数组进行排序Arrays.sort(nums);int n=nums.length;//1<<n就是该数组子集的个数for(int i=0;i<(1<<n);i++){List<Integer> list=new ArrayList<Integer>();for(int j=0;j<n;j++){//(i&(1<<j))!=0表示数组中索引值为j的数在当前的子集中if((i&(1<<j))!=0){list.add(nums[j]);}}result.add(list);}return result;    }}


0 0