I'm working on a problem that asks me to "Write a method that returns all of the subsets of the set formed by the integers 1 to N where N is passed to the method." If I pass N = 3 to the method my output should look like [[0], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]. My current output is [[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]. Is there a way for me to print out the desired range like doing Arrays.copyOfRange() for the ArrayList? or is there another way of getting the subset with my desired output?;
import java.util.ArrayList;
import java.util.HashSet;
public class HW3 {
public static void main(String[] args) {
System.out.println(powerset(3));
}
public static ArrayList<HashSet<Integer>> powerset(int N) {
ArrayList<HashSet<Integer>> arrayList = new ArrayList<HashSet<Integer>>();
HashSet<Integer> arrayListNew = new HashSet<Integer>();
for (int i = 0; i <= N; i++)
arrayListNew.add(i);
for (int i = 0; i < (int) Math.pow(2, N); i++)
arrayList.add(arrayListNew);
return arrayList;
}
}
