java求解 集合的子集
来源:互联网 发布:java fast paxos算法 编辑:程序博客网 时间:2024/05/22 10:20
方式1:我们知道子集个数 2的n次方
比如a,b,c的子集
* 000 0 {}
*001 1 a
*010 2 b
*011 3 a,b (b,a)
*100 4 c
* 101 5 a,c (c,a)
* 110 6 b,c (c,b)
* 111 7 a,b,c
利用二进制的对应关系
@Testpublic void test1() throws Exception {Set<ArrayList<Integer>> subsets = getSubsets( Arrays.asList(1,2,6));Set<ArrayList<String>> subsets2 = getSubsets( Arrays.asList("a","b","c"));Set<ArrayList<Character>> subsets3 = getSubsets( Arrays.asList('b','c','d'));System.out.println(subsets);System.out.println(subsets2);System.out.println(subsets3);}//集合接受各种类型数据public <T> Set<ArrayList<T>> getSubsets(List<T> subList) {//考虑去重Set<ArrayList<T>> allsubsets = new LinkedHashSet<>();int max = 1 << subList.size();for (int loop = 0; loop < max; loop++) {int index = 0;int temp = loop;ArrayList <T> currentCharList = new ArrayList<T>();//控制索引while (temp > 0) {if ((temp & 1) > 0) {currentCharList.add(subList.get(index));}temp >>= 1;index++;}allsubsets.add(currentCharList);}return allsubsets;}
方式2:归纳法
@Testpublic void testName() throws Exception {Set<List<Integer>> subsets2 = getSubsets2(Arrays.asList(1,2,3));System.out.println(subsets2);}//方式2 归纳法//从{}和最后一个元素开始,每次迭代加一个元素组成一个新的集合public Set<List<Integer>> getSubsets2(List<Integer> list) { if (list.isEmpty()) { Set<List<Integer>> ans=new LinkedHashSet<>(); ans.add(Collections.emptyList()); return ans; } Integer first=list.get(0); List<Integer> rest=list.subList(1, list.size()); Set<List<Integer>> list1 = getSubsets2(rest); Set<List<Integer>> list2 = insertAll(first, list1);// System.out.println(list1); System.out.println(list2); System.out.println("================"); return concat(list1, list2);} public Set<List<Integer>> insertAll(Integer first,Set<List<Integer>> lists){ // Set<List<Integer>> result=new LinkedHashSet<>(); for (List<Integer> list : lists) {List<Integer> copy=new ArrayList<>();copy.add(first);copy.addAll(list);result.add(copy);} return result;} //这样写可以不影响lists1,lists2的值 private Set<List<Integer>> concat(Set<List<Integer>> lists1,Set<List<Integer>> lists2) { Set<List<Integer>> temp=new LinkedHashSet<>(lists1); temp.addAll(lists2); return temp;}
阅读全文
0 0
- java求解 集合的子集
- 求解集合的子集
- 递归求解集合的所有子集
- C语言递归求解集合的所有子集
- 集合子集的一个Java算法
- java求集合的子集算法
- 连续正整数集合子集的java算法
- java编写求集合的全体子集
- 求解数组的所有子集
- 求集合的子集
- 求集合的子集
- 求集合的子集
- 集合的子集
- 集合的子集
- 集合的子集
- 求集合的子集
- 求集合的子集
- 牛客网 | 集合的子集
- js获取元素的偏移量offset
- (5) 什么是数据项--每天五分钟学习数据结构
- eclipse中tomcat能正常启动,可以访问页面,但是浏览器访问不了tomcat首页之tomcat配置问题
- Keras TFLearn TensorLayer实例【转】
- TensorFlow 实现Softmax Regression 识别数字
- java求解 集合的子集
- MainThread agent ERROR Could not determine hostname or ip address; proceeding.
- SolidWorks 2017 SP2 Premium Multilanguge Win64 1DVD
- 初次使用servlet实现对数据的增删改查
- JDK源码解析之LinkedList
- QT Basic 014 Model/View programming (模型、视图编程)
- mybatis缓存文件的配置
- Web测试方法大全
- Mac中允许任何来源的app安装