Given a collection of integers that might contain duplicates, nums, return all possible subsets.

Note:

  • Elements in a subset must be in non-descending order.
  • The solution set must not contain duplicate subsets.

For example,

If nums = [1,2,2],
a solution is:

[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]

思路:这一题比subsets多一了一道反复,详细代码例如以下:

public class Solution {
boolean[] b;
Set<String> set;
List<List<Integer>> list;
Set<String> set1;
public List<List<Integer>> subsetsWithDup(int[] nums) {
b = new boolean[nums.length];
set = new HashSet<String>();
list = new ArrayList<List<Integer>>();
set1 = new HashSet<String>(); Arrays.sort(nums);
count(nums,"",nums.length,0);
return list;
} private void count(int[] nums,String s,int n,int j){
//没有反复才加入
if(set.add(s)){
//以","切割数组
String[] sa = s.split(",");
List<Integer> al = new ArrayList<Integer>();
for(int i = 0; i < sa.length; i++){
if(sa[i].length() > 0){
al.add(Integer.parseInt(sa[i]));
}
}
Collections.sort(al);
if(set1.add(al.toString()))
list.add(al);
} for(int i = j; i < nums.length;i++){
if(!b[i]){
b[i] = true;
count(nums,s + "," + nums[i],n-1,i+1);
b[i] = false;
}
}
} }

以下这样的写法更简洁:

public class Solution {
List<List<Integer>> list;//结果集
List<Integer> al;//每一项
public List<List<Integer>> subsetsWithDup(int[] nums) {
list = new ArrayList<List<Integer>>();
al = new ArrayList<Integer>();
Arrays.sort(nums);
//排列组合
count(nums,al,0);
return list;
} private void count(int[] nums,List<Integer> al,int j){ list.add(new ArrayList<Integer>(al));//不反复的才加入 for(int i = j; i < nums.length;i++){
if(i == j || nums[i] != nums[i-1]){//去除反复
al.add(nums[i]);//加入
count(nums,al,i+1);
al.remove(al.size()-1);//去除。为下一个结果做准备
}
}
} }

最新文章

  1. Elasticsearch索引(company)_Centos下CURL增删改
  2. python 中的高级函数filter()
  3. thinkphp的CURD操作
  4. jquery 实现页面局部刷新ajax做法
  5. bzoj4561: [JLoi2016]圆的异或并
  6. 关于Java中获取当前系统时间
  7. jquery 插件模版
  8. ARP网关占用
  9. zencart 具体页面调用规则: $body_code变量解析
  10. TCP三次握手及其背后的缺陷
  11. 人类阅读的优越方式打印php数组
  12. Tomcat热部署SpringMVC项目出错
  13. HAProxy实现mysql负载均衡
  14. transient关键字详解
  15. powerdesigenr设置主外键颜色
  16. 七、vue语法补充二(动态组件 &amp; 异步组件、访问元素 &amp; 组件、混入)
  17. 机器学习理论基础学习15---条件随机场(CRF)
  18. [NN] 随机VS批训练
  19. [2018HN省队集训D1T3] Or
  20. Java学习笔记——继承、接口、多态

热门文章

  1. c语言中的rewind函数,Win CE 不支持,可用fseek函数替换
  2. 《Linux命令行与shell脚本编程大全 第3版》Linux命令行---25
  3. 《Linux命令行与shell脚本编程大全 第3版》Linux命令行---12
  4. 修饰符的范围+运算符优先级+构造方法特点+switch参数
  5. django+nginx+mod_wsgi+apache网站部署
  6. maven更换阿里云仓库
  7. sublime text3中成功使用bootstrap3
  8. 迷宫问题(DFS,BFS)
  9. (18) python 爬虫实战
  10. (4)django mtv模式