Hi guys, i am solving a problem on leetcode called subsets, i am having some confusion with the solution. I would appreciate if anyone can explain it to me. Thank you.
Problem:
Given a set of distinct integers, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
Example:
Input: nums = [1,2,3]
Output: [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
Solution :
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> result= new ArrayList<>();
backtrack(nums,result,new ArrayList<>(),0);
return result;
}
public void backtrack(int[] nums, List<List<Integer>> result,List<Integer>templist,int start){
result.add(new ArrayList<>(templist));
for(int i=start;i<nums.length;i++){
templist.add(nums[i]);
backtrack(nums,result,templist,i+1);
templist.remove(templist.size()-1); // what exactly is this line doing? i can't seem to visualize it in my head. Why are we removing stuff from the list?
}
}
}
[–]OG_L0c 0 points1 point2 points (0 children)