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.
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);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.