78 Subsets

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:

DSF:和combination 的方法一样,再加一个控制mem.size 的外层循坏!

 
  

package leetcode2;

 
  

import java.util.*;

 
  

public class subset {

 
  

   public static ArrayList<ArrayList<Integer>> subset(int[] n){

 
  

  ArrayList<ArrayList<Integer>> res=new ArrayList<ArrayList<Integer>>();

 
  

  ArrayList<Integer> mem=new ArrayList<Integer>();

 
  

  int deep=0;

 
  

  for(int i=0;i<=n.length;i++){

 
  

  dfs(res,mem,deep,n,i);

 
  

  }

 
  

  return res;

 
  

   }

 
  

public static void dfs(ArrayList<ArrayList<Integer>> res,

 
  

ArrayList<Integer> mem, int deep,int[] n,int i) {

 
  

// TODO Auto-generated method stub

 
  

if(mem.size()==i){

 
  

ArrayList<Integer> re= new ArrayList<Integer>(mem) ;

 
  

Collections.sort(re);

 
  

if(!res.contains(re)){

 
  

res.add(re);

 
  

}

 
  

return;

 
  

}

 
  

for(int i1=deep;i1<n.length;i1++){

 
  

mem.add(n[i1]);

 
  

dfs(res,mem,i1+1,n,i);

 
  

if(mem.size()>0){

 
  

mem.remove(mem.size()-1) ;

 
  

}

 
  

 

 
  

}

 
  

 

 
  

}

 
  

public static void main(String[] args) {

 
  

// TODO Auto-generated method stub

 
  

      int[] a={1,2,3,8};

 
  

      System.out.println(subset(a));

 
  

}

 
  

 

 
  

}

 

 

转载于:https://www.cnblogs.com/joannacode/p/4395966.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值