Subsets II

来源:互联网 发布:全站仪传输软件 编辑:程序博客网 时间:2024/05/20 04:51

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],  []]
与subsets不同的是数字可能重复 所以 在进行遍历时 相同数值的s[i]只能用一次 代码如下:
public class Solution {    public static List<List<Integer>> subsetsWithDup(int[] S) {Arrays.sort(S);List<List<Integer>> res=new ArrayList<List<Integer>>();for(int i=0;i<=S.length;i++){List<List<Integer>> resi=new ArrayList<List<Integer>>();List<Integer> tmp=new ArrayList<Integer>();Map<Integer,Integer> map=new HashMap<Integer,Integer>();ssubsets(resi, tmp, S, i, 0, map, 0);res.addAll(resi);}return res;}public static void ssubsets(List<List<Integer>> res, List<Integer> tmp,int[] s, int k, int count, Map<Integer, Integer> map, int index) {if(count==k){              res.add(tmp);              return;          }         int com=s[index]-1;        for(int i=index;i<s.length;i++){              if(s[i]==com) continue;            if(map.containsKey(i)) continue;              com=s[i];            Map<Integer,Integer> newMap=new HashMap<Integer,Integer>();              newMap.putAll(map);              newMap.put(i, 1);              List<Integer> newTmp=new ArrayList<Integer>();              newTmp.addAll(tmp);              newTmp.add(s[i]);              ssubsets(res, newTmp, s, k, count+1, newMap,i);          }  }}


0 0
原创粉丝点击