// Given a set of distinct integers, nums, return all possible subsets.
// Note: The solution set must not contain duplicate subsets.
// For example,
// If nums = [1,2,3], a solution is:
// [
// [3],
// [1],
// [2],
// [1,2,3],
// [1,3],
// [2,3],
// [1,2],
// []
// ]
public class Subsets {
public static List<List<Integer>> subsets(int[] nums){
List<List<Integer>> sets = new ArrayList<List<Integer>>();
sets.add(new ArrayList<Integer>());
if(nums.length==0){
return sets;//empty set
}
//iterate and add the respective element to the subsets of previous iteration
for(int i = 0; i<nums.length; i++){
int size = sets.size();
for(int j=0;j<size; j++){
List<Integer> newlist = new ArrayList<>(sets.get(j));
newlist.add(nums[i]);
sets.add(newlist);
}
}
return sets;
}
//recursive approach and is similar to SubsetsII problem
public List<List<Integer>> subsets2(int[] nums) {
//handle base case
List<List<Integer>> lists = new ArrayList<List<Integer>>();
//Arrays.sort(nums);
subsetsRecursive(lists, new ArrayList<Integer>(), nums, 0);
return lists;
}
public void subsetsRecursive(List<List<Integer>> lists, List<Integer> tempList, int[] nums, int start){
lists.add(new ArrayList<>(tempList));
for(int i=start; i<nums.length; i++){
tempList.add(nums[i]);
subsetsRecursive(lists, tempList, nums, i+1);
tempList.remove(tempList.size()-1);
}
}
}
// Note: The solution set must not contain duplicate subsets.
// For example,
// If nums = [1,2,3], a solution is:
// [
// [3],
// [1],
// [2],
// [1,2,3],
// [1,3],
// [2,3],
// [1,2],
// []
// ]
public class Subsets {
public static List<List<Integer>> subsets(int[] nums){
List<List<Integer>> sets = new ArrayList<List<Integer>>();
sets.add(new ArrayList<Integer>());
if(nums.length==0){
return sets;//empty set
}
//iterate and add the respective element to the subsets of previous iteration
for(int i = 0; i<nums.length; i++){
int size = sets.size();
for(int j=0;j<size; j++){
List<Integer> newlist = new ArrayList<>(sets.get(j));
newlist.add(nums[i]);
sets.add(newlist);
}
}
return sets;
}
//recursive approach and is similar to SubsetsII problem
public List<List<Integer>> subsets2(int[] nums) {
//handle base case
List<List<Integer>> lists = new ArrayList<List<Integer>>();
//Arrays.sort(nums);
subsetsRecursive(lists, new ArrayList<Integer>(), nums, 0);
return lists;
}
public void subsetsRecursive(List<List<Integer>> lists, List<Integer> tempList, int[] nums, int start){
lists.add(new ArrayList<>(tempList));
for(int i=start; i<nums.length; i++){
tempList.add(nums[i]);
subsetsRecursive(lists, tempList, nums, i+1);
tempList.remove(tempList.size()-1);
}
}
}
No comments:
Post a Comment