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 - 78 - Subsets(求数组全部子集)
- LeetCode 78 Subsets (所有子集)
- 两种回溯方法解决子集问题的思路 leetcode 78. Subsets
- 递归-数组的子集:leetcode 78 Subsets
- leetcode解题之 77. Combinations&78. Subsets&90. Subsets II java 版(求所有子集)
- leetcode78、90-Subsets I/II(组合数/子集数目)
- 【LeetCode】78. Subsets
- Leetcode 78. Subsets
- LeetCode 78 --- Subsets
- [LeetCode] 78. Subsets
- LeetCode 78 [Subsets]
- (java)leetcode-78:Subsets
- LeetCode 78:Subsets
- leetcode-78 Subsets
- LeetCode-78-Subsets(回溯法)-Medium
- LeetCode | Subsets(子集)
- LeetCode-Subsets(子集)
- 78. Subsets&集合的子集&Power Set
- [leetcode 78 & 90, Medium] Subsets I and II
- LeetCode 78: Subsets