题目:
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 = [1,2,2]
, a solution is:
[ [2], [1], [1,2,2], [2,2], [1,2], [] ]分析:
求子集,且子集元素从小到大排列,且不能有重复的
参考代码如下:
http://www.programcreek.com/2013/01/leetcode-subsets-ii-java/
从后往前挨个遍历,每次如果不是第一次,而且当前元素不等于前一个元素,获取当前结果集中的list列表prev,
将当前元素加到每个list的第一位;
如果当前元素跟前一个元素不相同,则把此单元素加入到prev当中
最后将此轮得到的新元素集合加入到结果集中!
public class Solution {
public List<List<Integer>> subsetsWithDup(int[] num) {
if (num == null)
return null;
Arrays.sort(num);
List<List<Integer>> result = new ArrayList<List<Integer>>();
List<List<Integer>> prev = new ArrayList<List<Integer>>();
for (int i = num.length-1; i >= 0; i--) {
//get existing sets
if (i == num.length - 1 || num[i] != num[i + 1] || prev.size() == 0) {
prev = new ArrayList<List<Integer>>();
for (int j = 0; j < result.size(); j++) {
prev.add(new ArrayList<Integer>(result.get(j)));
}
}
//add current number to each element of the set
for (List<Integer> temp : prev) {
temp.add(0, num[i]);
}
//add each single number as a set, only if current element is different with previous
if (i == num.length - 1 || num[i] != num[i + 1]) {
ArrayList<Integer> temp = new ArrayList<Integer>();
temp.add(num[i]);
prev.add(temp);
}
//add all set created in this iteration
for (List<Integer> temp : prev) {
result.add(new ArrayList<Integer>(temp));
}
}
//add empty set
result.add(new ArrayList<Integer>());
return result;
}
}