LeetCode Subsets II (带有重复元素的组合)
2015-06-20 10:04
573 查看
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 =
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], [] ]
题意:给出n个数,按非递减顺序给出,求其所有的组合
思路:与Subsets(求所有的组合)处理方法有些类似,只是在取一个元素时,分为取和不取两种情况,但是在元素有重复情况时,就分为取0, 1,2,...直到取n的情况,与元素重复的个数有关。
代码如下:
public class Solution { private List<List<Integer>> dfs(HashMap<Integer, Integer> m, int[] nums, int cur) { List<List<Integer>> res = new LinkedList<List<Integer>>(); /*空组合*/ if (cur == nums.length) { List<Integer> ans = new LinkedList<Integer>(); res.add(ans); return res; } /*表示从第cur+1到n之间的数生成的组合*/ List<List<Integer>> ret = dfs(m, nums, cur + 1); res.addAll(ret); /*第cur个数的出现次数*/ int num = m.get(nums[cur]); for (List<Integer> list : ret) { List<Integer> tmp2 = new LinkedList<Integer>(); tmp2.addAll(list); /*表示第cur个数取1个直到取num个的处理*/ for (int i = 0; i < num; i++) { List<Integer> tmp = new LinkedList<Integer>(); tmp2.add(0, nums[cur]); tmp.addAll(tmp2); res.add(tmp); } } return res; } public List<List<Integer>> subsetsWithDup(int[] nums) { /*统计每个数的出现次数*/ HashMap<Integer, Integer> hs = new HashMap<Integer, Integer>(); for (int i = 0, len = nums.length; i < len; i++) { if (hs.containsKey(nums[i])) { int value = hs.get(nums[i]); hs.put(nums[i], value + 1); } else { hs.put(nums[i], 1); } } int[] array = new int[hs.size()]; int i = 0; for (Integer a : hs.keySet()) { array[i++] = a; } return dfs(hs, array, 0); } }
相关文章推荐
- Leetcode:Partition List
- MySQL详解(3)----------运算符
- 正则式(二)
- Lua cjson模块编译笔记及错误解决方法
- android点滴记录
- mysql 安装后无法登陆mysql的 shell 那mysql>经验:ERROR 1045 (28000): Access denied for user 'root'@'localhost‘
- Objective-C----多态
- 《人,绩效和职业道德》读后感
- C++ Primer Plus学习笔记四(第四章)
- Python爬取某贴吧第一页的所有帖子的标题、连接、作者,将数据储存到txt文件中
- Hadoop 命令行运行实例
- SQL 学习记录
- spark_job_server
- To_10_r_100_8_2---如果你只能将金条切割两次,你怎样分给这些工人?
- Android数据库高手秘籍(八)——使用LitePal的聚合函数
- Objective-C----autorelease pool
- matlab中周期图功率谱法的实现原理
- Sqrt(x) - LeetCode 69
- Android数据库高手秘籍(七)——体验LitePal的查询艺术
- SASS用法指南