Subsets II

来源:互联网 发布:远程协助软件steam 编辑:程序博客网 时间:2024/06/05 02:24
题目:

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 setsif (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 setfor (List<Integer> temp : prev) {temp.add(0, num[i]);} //add each single number as a set, only if current element is different with previousif (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 iterationfor (List<Integer> temp : prev) {result.add(new ArrayList<Integer>(temp));}} //add empty setresult.add(new ArrayList<Integer>()); return result;  }}



0 0
原创粉丝点击