My question is:
ArrayList temp = new ArrayList(r);
Without this line, I am inserting nothing into res
As the other answer said, doing:
res.add(r)
Adds a reference to the same object r
is referring to, into the list. Effectively, what happens here is:
r
refers to a listadd
res
But notice that both r
and the reference inside res
are referring to the same object
When you do the thing with the temp
what happens is:
r
.temp
add
res
So now r
points to the original copy of the list, and the reference inside res
points to the new copy of it. They are two distinct objects.
Why is this important?
Basically, your recursive step adds one element to r
, calls find
again, and then removes one element from r
. The reference in r
and res
are passed down the recursion so it means those two same objects are passed down the recursion.
But since after you return from the recursion, you actively remove one object from r
, it means that at the end, when you go all the way up, there will be no more elements inside r
.
Since the reference stored inside res
is pointing to the same object r
is pointing to, not to a copy of it, it means that when you remove an item using r.remove()
, that object becomes empty. But that's the same object that we are referring to from inside res
. So at the end of the recursion, it will be empty.
Think of it like a safe. Person A fills the safe with money. Then he gives person B a second key to the safe. Then he goes in with his original key, and takes out all the money. When B comes and opens the safe, it is empty!
Copying the list is the equivalent of A giving B his own money to put in his own safe. A can remove as much money as he wants from his own safe, and it won't change the amount of money in B's safe.