您的位置:首页 > 其它

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