My solution in Java. But I don't know WHY I have to create new list on line 14

  • 1
    public class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> ans = new ArrayList<>();
        List<Integer> path = new ArrayList<Integer>();
        if (nums == null || nums.length == 0) return ans;
        subsetsHelper(nums, path, ans, 0);
        return ans;
    public void subsetsHelper(int[] nums, List<Integer> path, List<List<Integer>> ans, int pos) {
        ans.add(new ArrayList<Integer>(path)); //**WHY I HAVE TO CREATE NEW LIST HERE???**
        for (int i = pos; i < nums.length; i++) {
            subsetsHelper(nums, path, ans, i + 1);
            path.remove(path.size() - 1);


    Is it related to Pass-By-Value? Someone plz help me here! Thanks

  • 2

    A new deep copy reference is needed at each level of the recursive stack otherwise you will be operating on the same path Object the whole time. This means when calling path.add(...) and path.remove(...) this will effect the list you have added to ans a list of list. You do not want this behavior at all once you add a list to ans you don't want that list modified anymore.

    Update for useful link
    java pass by value explanation

  • 0

    Thanks! I see your point. Can you explain this more directly via the perspective of pass-by-value and pass-by-reference? Because I thought if Java is pass-by-value, that line (line 14) should add a copy of 'path' to 'ans', which shouldn't be affected by the later on path.add(...) or path.remove(...).
    These basic reference or pointer staff is killing me...

  • 0

    I had the same issues first starting. I'll give you a brief explanation in this comment but I'll update my original answer with a link that helped me tremendously. OK first there is no such thing as pass by reference in Java you are right EVERYTHING is pass by value. OK here is where it gets interesting. ALL object values in Java are references. Think about this for a second a reference means the object is really just a pointer in memory. So in line 14 if you don't use new what you are doing is passing a pointer to the same place in memory this means when you change it in one spot that changes it everywhere. Now if you create a new object in line 14 these references point to different objects all together. Look at the linked in my answer. Keep reading the answers until it makes sense to you

  • 0

    Thank you! This is really helpful. I think I'm clear about this now

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.