90 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],
[]
]

1. 对数组进行排序
2. 从前往后依次遍历数组中的元素
3. 遍历列表中现存的每个子集，使它们分别加上当前遍历到的数组元素，形成一个个新的子集
4. 列表中的初始子集就是数组遍历到的第一个元素

public class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> res = new ArrayList();
if(nums == null || nums.length == 0)
return res;
Arrays.sort(nums);
int start = 0;
int n = 0; // 记录上一轮新添加的子集个数
for(int i = 0; i < nums.length; i ++) {
int size = res.size();
if(i > 0 && nums[i - 1] == nums[i])
start = size - n;
else
start = 0;
n = 0;
for(int j = start; j < size; j ++) {
List<Integer> elem = new ArrayList(res.get(j));
n ++;
}
}
return res;
}
}
19 / 19 test cases passed.
Status: Accepted
Runtime: 3 ms

public class Solution {
public List<List<Integer>> subsetsWithDup(int[] num) {
List<List<Integer>> res = new ArrayList();
if(num==null || num.length==0)
return res;
Arrays.sort(num);
int start = 0;
for(int i=0;i<num.length;i++)
{
int size = res.size();
for(int j=start;j<size;j++)
{
List<Integer> newItem = new ArrayList<Integer>(res.get(j));
}
if(i<num.length-1 && num[i]==num[i+1])
{
start = size;
}
else
{
start = 0;
}
}
return res;
}
}
19 / 19 test cases passed.
Status: Accepted
Runtime: 3 ms

• 本文已收录于以下专栏：

举报原因： 您举报文章：90 Subsets II 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)