Subsets

来源:互联网 发布:淘宝上6s主板是真的吗 编辑:程序博客网 时间:2024/06/14 12:05

Given a set of distinct integers, 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,3], a solution is:

[  [3],  [1],  [2],  [1,2,3],  [1,3],  [2,3],  [1,2],  []]
是 Combination的升级版只要从0-S.length依次执行Combination的操作即可 注意的是 要先对数组进行排序代码如下:
public class Solution {    public static List<List<Integer>> subsets(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;          }          for(int i=index;i<s.length;i++){              if(map.containsKey(i)) continue;              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