I am trying to create the subsets of the given array {1,2,3,4,5} in an iterative way. hence, I am using this code:
import java.util.ArrayList;
import java.util.Scanner;
public class Subsets {
public static void main(String[] args) {
int [] weights = new int[] {1,2,3,4,5};
ArrayList<ArrayList<Integer>> subsets = new ArrayList<>();
subsets.add(new ArrayList<>());
for(int i =0; i<weights.length;i++){
System.out.println("New loop");
ArrayList<ArrayList<Integer>> temp;
System.out.println("in subsets");
for(int k = 0;k<subsets.size();k++)
{
System.out.println(subsets.get(k));
}
temp = subsets;
for(int j=0;j<temp.size();j++){
System.out.println("dsdf"+ temp.get(j));
(temp.get(j)).add(weights[i]);
//subsets.add(temp.get(j));
System.out.println("After adding:" + temp.get(j));
}
System.out.println("In temp");
for(ArrayList<Integer> a: temp){
System.out.println(a);
}
subsets.addAll(temp);
I start with subset = [] for each element in array: I do temp = subset //[] do another loop with j till the size of temp = 1
Addarray[i] to temp[j] == [[1]] add this temp to subset = [[],[1]]instead my subset becomes = [[1],[1]]
Also in another run for i = array[1] = 2 temp should traverse each element of subset; so add arra[i] to each element of temp making it [1], [1,2], instead it is [1,2,2],[1,2,2]
changing the entire temp in one insertion
Can anyone tell me where am I wrong"
Thank you