Skip to content

Instantly share code, notes, and snippets.

@WOLOHAHA
Created August 8, 2014 08:49
Show Gist options
  • Save WOLOHAHA/a2e81f86ba1df6607519 to your computer and use it in GitHub Desktop.
Save WOLOHAHA/a2e81f86ba1df6607519 to your computer and use it in GitHub Desktop.
Write a method to return all subsets of a set.
package POJ;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main{
/**
*
* 9.4 Write a method to return all subsets of a set.
*
*
*/
public static void main(String[] args) {
Main so = new Main();
int[] s={0,1,2};
List<List<Integer>> RESULT=so.subsets(s);
for(List<Integer> temp:RESULT){
for(int i=0;i<temp.size();i++)
System.out.print(temp.get(i)+" ");
System.out.println();
}
}
public List<List<Integer>> subsets(int[] S) {
List<List<Integer>> result=new ArrayList<List<Integer>>();
List<Integer> tmp=new ArrayList<Integer>();
result.add(tmp);
Arrays.sort(S);
dfs(result,tmp,S,0);
return result;
}
private void dfs(List<List<Integer>> result, List<Integer> tmp, int[] s,int depth) {
// TODO Auto-generated method stub
for(int i=depth;i<s.length;i++){
tmp.add(s[i]);
result.add(new ArrayList<Integer>(tmp));
dfs(result,tmp,s,i+1);
tmp.remove(tmp.size()-1);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment