Subsets II Java

来源:互联网 发布:淘宝怎么看行业分析 编辑:程序博客网 时间:2024/05/17 21:45

Given a collection of integers that might contain duplicates, S, 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 S = [1,2,2], a solution is:

[  [2],  [1],  [1,2,2],  [2,2],  [1,2],  []]

 Extension of Subsets problem, only difference is we
    need to skip elements if there is duplication was found
    by define loop j start from certain index which is set up index=size
    if there is duplication was found,else index=0


public class Solution {   public static ArrayList<ArrayList<Integer>> subsetsWithDup(int[] num) {        ArrayList<ArrayList<Integer>> res=new ArrayList<ArrayList<Integer>>();        if(num.length==0) return res;        Arrays.sort(num);        int index=0;        ArrayList<Integer> list=new ArrayList<Integer>();        res.add(list);        for(int i=0;i<num.length;i++){            int size=res.size();            for(int j=index;j<size;j++){                list=new ArrayList<Integer>(res.get(j));                list.add(num[i]);                res.add(list);            }            if(i<num.length-1 && num[i]==num[i+1]){                  index=size;            }else {                index=0;            }        }        return res;    }}

0 0
原创粉丝点击