0

I am having difficulty understanding this code.


class Solution {
    public List<List<Integer>> subsets(int[] nums) {
     List<List<Integer>> subsets = new ArrayList<>();
     generateSubsets(0, nums, new ArrayList<Integer>(), subsets);
     return subsets;
    }
    public void generateSubsets(int index, int[] nums, List<Integer> current, List<List<Integer>> subsets){
        subsets.add(new ArrayList<>(current));
        for(int i = index; i < nums.length; i++){
            current.add(nums[i]);           
            generateSubsets(i + 1, nums, current, subsets);
            current.remove(current.size()-1);
          
        }
    }
}


I don't understand how this code will run this code at each step. If we take an example input [1,2,3]. I think first I would get the current list [1], then a recursive call and new current list is [1,2] then a new recursive call and current list is [1,2,3] but I am very confused what the next steps would be.

I would really appreciate it if someone could walk me through this process. Especially when the code current.remove(current.size()-1); is hit.

Thank you very much.

kr214229
  • 29
  • 4

1 Answers1

0

Set break points at the lines of interest and use your IDE to debug. Just for a starter you could also put some println statments to follow the recursive code flow:

public static void generateSubsets(int index, int[] nums, List<Integer> current, List<List<Integer>> subsets){
    System.out.println("\nrecursive method called with index: " + index + " current list: " + current);
    subsets.add(new ArrayList<>(current));
    System.out.println("subsets after adding current: " + subsets);
    for(int i = index; i < nums.length; i++){
        System.out.println("entering loop at index: " + index);
        current.add(nums[i]);
        System.out.println("current after adding current index: " + current);
        generateSubsets(i + 1, nums, current, subsets);
        current.remove(current.size()-1);
        System.out.println("current after removing last element back at index: "+ index + " " +current);
    }
}
Eritrean
  • 15,851
  • 3
  • 22
  • 28
  • 1
    Thank you for your response. I have set break points throughout my code and it really helped! I am still stuck at this part: "Subsets after adding current: [ [], [1], [1,2], [1,2,3] ]" But then after removing last element at back of index twice we end up with [1,3]. I don't understand how we get [1,3]. If you could maybe elaborate on that I would greatly appreciate. – kr214229 Aug 28 '22 at 21:38
  • 1
    The reason you get `[1,3]` is because after the `[1,2,3]` bubbles back up to the `[1,2]` call, the next step in the loop is to remove the last element `2`, then `i` becomes 3, and you get `[1,3]`. – William Fleetwood Aug 29 '22 at 01:29
  • Thank you William Fleetwood for your response. Could you please elaborate how ```i ``` becomes 3? I am getting lost at how ```i``` actually backtracks. – kr214229 Aug 29 '22 at 23:18