Skip to content

Instantly share code, notes, and snippets.

@Chen-tao
Created January 28, 2017 09:14
Show Gist options
  • Save Chen-tao/81691eaf8443d576f45370be75b62306 to your computer and use it in GitHub Desktop.
Save Chen-tao/81691eaf8443d576f45370be75b62306 to your computer and use it in GitHub Desktop.
//https://leetcode.com/problems/subsets/
//一种思路
public class Solution {
/*
* Given a set S of n distinct integers, there is a relation between Sn and Sn-1. The subset
* of Sn is the union of subset of Sn-1 and each element in Sn-1 + one more element.
* Therefore, a Java solution can be quickly formalized.
*/
public static List<List<Integer>> ans = new ArrayList<List<Integer>>();
public List<List<Integer>> subsets(int[] nums) {
ans.clear();
if(nums == null){
return null;
}
Arrays.sort(nums);
for(int i = 0;i<nums.length;i++){
List<List<Integer>> tmp = new ArrayList<List<Integer>>();
for(List<Integer> a : ans){
tmp.add(new ArrayList(a));
}
for(List<Integer> t : tmp){
t.add(nums[i]);
}
List<Integer> single = new ArrayList<Integer>();
single.add(nums[i]);
tmp.add(single);
ans.addAll(tmp);
}
ans.add(new ArrayList<Integer>());
return ans;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment