LeetCode Subsets II
2015-09-27 10:02
363 查看
原题链接在这里:https://leetcode.com/problems/subsets-ii/
题目:
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 =
题解:
是Subsets的进阶版本。这里有duplicates, e.g. [1,2,2]但是res中不能包含两个[2].
所以在elem加完新元素想要放回res之前,需要先判断res中是否含有这个elem, 若是没有可以加到res中,若是已经有了,就不可以加到res中。
AC Java:
题目:
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的进阶版本。这里有duplicates, e.g. [1,2,2]但是res中不能包含两个[2].
所以在elem加完新元素想要放回res之前,需要先判断res中是否含有这个elem, 若是没有可以加到res中,若是已经有了,就不可以加到res中。
AC Java:
public class Solution { public List<List<Integer>> subsetsWithDup(int[] nums) { List<List<Integer>> res = new ArrayList<List<Integer>>(); if(nums == null || nums.length == 0){ return res; } Arrays.sort(nums); res.add(new ArrayList<Integer>()); for(int i = 0; i<nums.length; i++){ int size = res.size(); for(int j = 0; j<size; j++){ ArrayList<Integer> elem = new ArrayList<Integer>(res.get(j)); elem.add(nums[i]); if(!res.contains(elem)){ res.add(elem); } } } return res; } }
相关文章推荐
- 23种设计模式
- C++机器学习古典材料
- 单例模式的疑问
- ID3算法
- 剑指 offer:栈的压入、弹出序列
- vim插件管理利器——vundle
- extern c
- [转载]Java程序员掌握的10大项知识体系--精通太难说出口
- 数据库的事务ACID性质
- JDBC连接数据库的步骤
- cookie和session
- Spinner的setOnItemSelectedListener不起作用
- 用 CocoaPods 安装 React Native
- 约瑟夫问题(数到3出局)----链表操作
- ztree (一)----初体验
- Java_基础_参数传递
- jQuery源码分析之jQuery.Event,$.stopImmediatePropagation,$.preventDefault,$.stopPropagation
- 负载均衡之lvs
- Django模板:HTML静态模板的继承
- ant安装和配置