Search code examples
javaalgorithmbacktracking

Values not getting added in the global ArrayList in java


I'm solving this problem on interviewbit and logically I've solved it using backtracking but I'm not able to add values in the ArraList which I defined outside main function. My code looks something like this:

import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
class main {
    public static ArrayList<ArrayList<Integer>> solution = new ArrayList<ArrayList<Integer>>();

    public static ArrayList<ArrayList<Integer>> subsets(ArrayList<Integer> A) {
        if(A.size() == 0){
            return new ArrayList<ArrayList<Integer>>();
        }
        Collections.sort(A);

        ArrayList<Integer> subset = new ArrayList<Integer>();
        solution.add(subset);
        subsetsUtil(A, subset, 0);
        return solution;
    }

    public static void subsetsUtil(ArrayList<Integer> A, ArrayList<Integer> subset, int index) {
        for(int i=index; i<A.size(); i++) {
            //including the element
            subset.add(A.get(i));
            solution.add(subset);
            subsetsUtil(A, subset, i+1);
            //excluding the element
            subset.remove(subset.size() - 1);
        }
    }

    public static void main(String args[]) {
        Scanner input = new Scanner(System.in);
        int n = input.nextInt();

        ArrayList<Integer> A = new ArrayList<Integer>();
        for(int i=0;i<n;i++) {
            A.add(i + 1);
        }
        System.out.println(subsets(A));
    }
}

Here I've declared the solution as an arrayList outside all the functions but whenever I'm adding an array list to this list. It is not getting added. For input = 3, the solution is [[], [], [], [], [], [], [], []] which should be something like this :

[]
[1]
[1, 2]
[1, 2, 3]
[1, 3]
[2]
[2, 3]
[3]

But if I print the subset values in subsetUtils function, it is fine.


Solution

  • All the subset lists you add to the solution are the same instance. Which is gradually getting mutated until it has no elements.

    change:

    solution.add(subset);
    

    to:

    solution.add(new ArrayList<>(subset));