Hello guys! I was doing an assessment and got a problem about subset numbers. for example if I have {1,2,3}, it should be printed as : [[], [1], [2], [1,2], [3],[1,3],[2,3],[1,2,3]] and if {0} it should print [[],[0]]. After spending like an hour stuck like hell with this 😵💫 I came up with a function :
public class Main {
public static List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
result.add(new ArrayList<>());
for (int num : nums) {
for (int i = 0; i < result.size(); i++) {
List<Integer> subset = new ArrayList<>(result.get(i));
subset.add(num);
result.add(subset);
}
}
return result;
}
public static void main(String[] args) {
System.out.println(subsets(new int[]{1,2,3}));
}
}
when I run this code I don't anything ! however when I the result.size() in a variable like int size = result.size(); it works!