您的位置:首页 > 其它

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 =
[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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: