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.