0

I have the following code:

class Solution {
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        permuteUtil(new ArrayList<Integer>(), nums, result);
        return result;
    }

    public void permuteUtil(List<Integer> current, int[] nums, List<List<Integer>> result){
        if(current.size() == nums.length){
            result.add(current);
        }
        for(int i=0; i<nums.length; i++){
            if(!current.contains(nums[i])){
                current.add(nums[i]);
                permuteUtil(current, nums, result);
                current.remove(current.size()-1);
            }
        }
    }
}

I am modifying the current list and adding it to result set, however when current.size() == nums.length condition is fulfilled, an empty list gets added to result.

But when I create a new list from current and add it to result, it works fine. result.add(new ArrayList<>(current))

Please help me understand what exactly happens when I try to add current directly to result.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • Java is pass-by-value, but the value that is passed is the reference to the object (in this case the list), given `permuteUtil` modifies the list passed in by adding a value to the list, calling `permuteUtil`, and then **removing** a value from the list, the end result is an empty list, because ultimately it is one and the same list. You'll end up with a list with multiple reference to the same, empty, list. – Mark Rotteveel Mar 04 '23 at 07:07

0 Answers0