博客
关于我
非空子集《算法很美》
阅读量:545 次
发布时间:2019-03-08

本文共 1399 字,大约阅读时间需要 4 分钟。

非空子集

思路: 其实主要理解HashSet即可,利用HashSet集合的不重复原则。

利用HashSet嵌套

public Set
> getSubsets2(int[] A, int n) { Set
> res = new HashSet<>(); Set
res_new = new HashSet<>(); res_new.add(1); res_new.add(1); res_new.add(2); res_new.add(3); res.add(res_new);//初始化为空集 return res;}结果为:[[1, 2, 3]]

具体思路:

创建一个大集合res,里面嵌套着一个小集合,然后遍历,每次遍历要把原本的子集和放到大集合里面,然后再遍历,将之前的元素拷贝到当前元素中。

结果:[[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]

例如:

[1,2]是将[1]拷贝到[2]中,形成[1,2]。[1, 3], [2, 3], [1, 2, 3]是将[1],[2],[1,2]分别拷贝到[3]中形成的。
public class 非空子集 {       public static void main(String[] args){           int[] A = {   1, 2, 3};        Set
> subsets2 = new 非空子集().getSubsets2(A, A.length); System.out.println(subsets2); } /*逐步生成迭代大法*/ public Set
> getSubsets2(int[] A, int n) { Set
> res = new HashSet<>(); res.add(new HashSet<>());//初始化为空集 //从第一个元素开始处理 for (int i = 0; i < n; i++) { Set
> res_new = new HashSet<>();//新建一个大集合 res_new.addAll(res);//把原来集合中的每个子集都加入到新集合中 //遍历之前的集合,全部克隆一遍 for (Set e : res) { Set clone = (Set) ((HashSet) e).clone(); clone.add(A[i]);//把当前元素加进去 res_new.add(clone);//把克隆的子集加到大集合中 } res = res_new; } return res; }}结果:[[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]

知识点: clone() 方法。

clone() 方法用于复制一份 hashMap,属于浅拷贝。

转载地址:http://cwanz.baihongyu.com/

你可能感兴趣的文章
MySQL:索引失效场景总结
查看>>
Mysql:避免重复的插入数据方法汇总
查看>>
MyS中的IF
查看>>
M_Map工具箱简介及地理图形绘制
查看>>
m_Orchestrate learning system---二十二、html代码如何变的容易
查看>>
M×N 形状 numpy.ndarray 的滑动窗口
查看>>
m个苹果放入n个盘子问题
查看>>
n = 3 , while n , continue
查看>>
n 叉树后序遍历转换为链表问题的深入探讨
查看>>
N!
查看>>
N-Gram的基本原理
查看>>
n1 c语言程序,全国青少年软件编程等级考试C语言经典程序题10道七
查看>>
Nacos Client常用配置
查看>>
nacos config
查看>>
Nacos Config--服务配置
查看>>
Nacos Derby 远程命令执行漏洞(QVD-2024-26473)
查看>>
Nacos 与 Eureka、Zookeeper 和 Consul 等其他注册中心的区别
查看>>
Nacos 单机集群搭建及常用生产环境配置 | Spring Cloud 3
查看>>
Nacos 启动报错[db-load-error]load jdbc.properties error
查看>>
Nacos 报Statement cancelled due to timeout or client request
查看>>