1
import java.util.ArrayList;`
public class Main{
 public static void main(String[] args) {
        ArrayList<Integer> nums = new ArrayList<>();
        List<List<Integer>> list= new ArrayList<>();
        int[] arr = {2,3,5};
      subset(list,nums,arr,0);
        System.out.println(list);
    } 
static void subset(List<List<Integer>> list,ArrayList<Integer> nums,int[] arr, int index){
        if(index==arr.length){
          list.add(nums);
            return  ;
    }
        int c= arr[index];
        nums.add(c);
      subset(list,nums,arr,index+1);
        nums.remove(nums.size()-1);
       subset(list,nums,arr, index+1);
   return ;
    }
}`type here

output={[],[],[],[],[],[],[],[],[]} expected={[2,3,5],[2,3],[2,5],[2],[3,5],[3],[5],[]} can anyone tell me why it is giving empty list ?

I wrote a program for returning a list containing lists of subsets of a given array using backtracking and recursion , I called a function named subset of void returntype where I was adding elements ie, subsets in the list (containing subsets of a set) and expecting to then print that list after coming out of the function but it is giving me list of empty lists ie, {[],[],[],[],[],[],[],[]} , can anyone please help me solving this problem.

1 Answers1

1

When you add nums to list using list.add(nums), you are actually adding a reference to the nums ArrayList. This means that when you modify nums later on by adding or removing elements, those changes will also be reflected in the subsets already added to list. As a result, all subsets in list end up being the same, which is an empty list at the end of your recursion.

To fix that, you need to create a new ArrayList and add a copy of nums to list instead of adding the reference directly. This way, each subset in list will be independent of the changes made to nums afterwards.

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Integer> nums = new ArrayList<>();
        List<List<Integer>> list = new ArrayList<>();
        int[] arr = {2, 3, 5};
        subset(list, nums, arr, 0);
        System.out.println(list);
    }

    static void subset(List<List<Integer>> list, List<Integer> nums, int[] arr, int index) {
        if (index == arr.length) {
            list.add(new ArrayList<>(nums)); // Add a copy of nums to list
            return;
        }

        int c = arr[index];
        nums.add(c);
        subset(list, nums, arr, index + 1);
        nums.remove(nums.size() - 1);
        subset(list, nums, arr, index + 1);
    }
}

Output:

[[2, 3, 5], [2, 3], [2, 5], [2], [3, 5], [3], [5], []]
zoldxk
  • 2,632
  • 1
  • 7
  • 29