I am really curios about one thing when compiling, in the given code below, where I am creating nested for loop, I am giving as a limit
subsetArr.size()
but when compiling it is saying memory exceeded, and if I define size just before the for loop
int size = subsetArr.size()
and then passing limit as size
i<size;
it is working fine. What can be the cause?
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> subsetArr = new ArrayList<>();
subsetArr.add(new ArrayList());
for(int num: nums){
for(int i=0; i<subsetArr.size(); i++){
List<Integer> takenList = new ArrayList<>(subsetArr.get(i));
takenList.add(num);
subsetArr.add(takenList);
}
}
return subsetArr;
}
}
>Solution :
Look at what this loop does:
for(int i=0; i<subsetArr.size(); i++){
List<Integer> takenList = new ArrayList<>(subsetArr.get(i));
takenList.add(num);
subsetArr.add(takenList); // <-- here
}
Each iteration adds to the collection. So in the next iteration, subsetArr.size() will be larger. Thus you have a loop which indefinitely increases the size of the collection until it runs out of resources.
Contrast that to when you store the value:
int size = subsetArr.size();
In this case, while subsetArr.size() may change, size won’t unless you update it. So as long as you don’t update size then you have a finite loop.