您的位置:首页 > 其它

Leetcode 78 Subsets(打印全部子集)

2016-11-01 16:06 399 查看

一,问题描述

1,给定一个整数集合(集合元素具有相异性),求出所有的子集合。

2,例如给定集合为[1,2,3]

输出:

[3]

[1]

[2]

[1 2 3]

[1, 3]

[2 ,3]

[1, 2]

[]

3,解题思路:

使用位操作,不使用递归。首先,计算一下该数组nums一共有多少个子集,设数组nums的长度为n,那么它的子集总数为num=2^n。

设置一个变量index,其初始值为1。那么从0到2^n-1中数,对于每一个数i,用index与这个i比较,如果得出的结果大于0,则把该数输入到List<>中取,比较n次,因为数组的长度为n。

二,AC了的程序(用Java实现的)

import java.util.*;
public class Test2{
public List<List<Integer>> subsets(int []nums)
{
List<List<Integer>> list=new ArrayList<List<Integer>>();
if(nums==null||nums.length==0)
{
return list;
}

int n=nums.length;  //数组的长度
int num=(int)Math.pow(2,n);

for(int i=0;i<num;i++)  //这里是2^n次的
{
int index=1;
List<Integer> temp=new ArrayList<Integer>();
for(int j=0;j<n;j++)  //数组的长度
{
int data=i&index;  //一共要计算num*n次的位与操作
System.out.println("data="+data);
if(data>0)//选取data大于0的数,说明该数还没有被选择过的。
{
temp.add(nums[j]);
}
index=index<<1;//左乘2的1次方
}
list.add(temp);
}

return list;

}

public static void main(String []args)
{
Test2 test=new Test2();
Scanner scan=new Scanner(System.in);
int n=scan.nextInt();
int []data=new int
;
for(int i=0;i<n;i++)
{
data[i]=scan.nextInt();
}

List<List<Integer>> list1=test.subsets(data);
Iterator<List<Integer>> it1=list1.iterator();
while(it1.hasNext())
{
List<Integer> list2=it1.next();
Iterator<Integer> it2=list2.iterator();
while(it2.hasNext())
{
int result=it2.next();
System.out.print(result+" ");
}
System.out.println();
}

}
}


运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode