博客
关于我
非空子集《算法很美》
阅读量: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/

你可能感兴趣的文章
mysql8 配置文件配置group 问题 sql语句group不能使用报错解决 mysql8.X版本的my.cnf配置文件 my.cnf文件 能够使用的my.cnf配置文件
查看>>
MySQL8.0.29启动报错Different lower_case_table_names settings for server (‘0‘) and data dictionary (‘1‘)
查看>>
MYSQL8.0以上忘记root密码
查看>>
Mysql8.0以上重置初始密码的方法
查看>>
mysql8.0新特性-自增变量的持久化
查看>>
Mysql8.0注意url变更写法
查看>>
Mysql8.0的特性
查看>>
MySQL8修改密码报错ERROR 1819 (HY000): Your password does not satisfy the current policy requirements
查看>>
MySQL8修改密码的方法
查看>>
Mysql8在Centos上安装后忘记root密码如何重新设置
查看>>
Mysql8在Windows上离线安装时忘记root密码
查看>>
MySQL8找不到my.ini配置文件以及报sql_mode=only_full_group_by解决方案
查看>>
mysql8的安装与卸载
查看>>
MySQL8,体验不一样的安装方式!
查看>>
MySQL: Host '127.0.0.1' is not allowed to connect to this MySQL server
查看>>
Mysql: 对换(替换)两条记录的同一个字段值
查看>>
mysql:Can‘t connect to local MySQL server through socket ‘/var/run/mysqld/mysqld.sock‘解决方法
查看>>
MYSQL:基础——3N范式的表结构设计
查看>>
MYSQL:基础——触发器
查看>>
Mysql:连接报错“closing inbound before receiving peer‘s close_notify”
查看>>