递归方法调用,求解集合的所有子集。
package ch01; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; public class QuerySubSet { public static List<Set<Object>> Query(Set<Object> target) { if(target.size() == 0) { List<Set<Object>> list= new LinkedList<Set<Object>>(); list.add(target); return list; }else if(target.size() == 1) { List<Set<Object>> list= new LinkedList<Set<Object>>(); list.add(target); Set<Object> nullset=new HashSet<Object>(); list.add(nullset); return list; }else { Iterator<Object> iter=target.iterator(); Object elem=iter.next(); target.remove(elem); Set<Object> newSet=new HashSet<Object>(); newSet.add(elem); List<Set<Object>> list1=Query(newSet); List<Set<Object>> list2=Query(target); return merge(list1, list2); } } public static List<Set<Object>> merge(List<Set<Object>> list1, List<Set<Object>> list2) { List<Set<Object>> mlist=new LinkedList<Set<Object>>(); for(Set<Object> set1: list1 ) for(Set<Object> set2: list2) { Set<Object> newSet=new HashSet(); newSet.addAll(set1); newSet.addAll(set2); mlist.add(newSet); } return mlist; } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Set<Object> targ=new HashSet<Object>(); for(int i=0; i<10; i++) { targ.add(Integer.toString(i)); } List<Set<Object>> allsubset= QuerySubSet.Query(targ); boolean f1=true; for(Set<Object> set1: allsubset) { if(!f1) System.out.print(","); f1=false; System.out.print("{"); boolean f2=true; for(Object obj: set1) { if(!f2) System.out.print(","); f2=false; System.out.print(obj.toString()); } System.out.println("}"); } } }
时间: 2024-10-12 22:23:23