I have one question about adding one Arraylist of Strings into another Arraylist, the code is the following:
public List<List<Integer>> combinationSum(int[] candidates,int target){
List<List<Integer>> res=new ArrayList<>();
Arrays.sort(candidates);
List<Integer>tempList=new ArrayList<>();
backtrack(res,tempList,candidates,target,0);
return res;
}
public void backtrack(List<List<Integer>>res, List<Integer>tempList,
int[]nums, int remain, int start){
if(remain==0) res.add(new ArrayList<>(tempList));
if(remain<0) return;
for(int i=start;i<nums.length;i++){
tempList.add(nums[i]);
backtrack(res,tempList,nums,remain-nums[i],i);
tempList.remove(tempList.size()-1);
}
}
I am wondering in the function of "backtrack", why we need to use the new Arraylist(tempList) when we want to add the tempList into the res Arraylist. Why can not we just put the tempList into res, like if(remain==0) res.add(tempList),since I thought tempList was already declared as an arraylist before and passed as one argument. Thank you.
new Arraylist(tempList)is creating a copy of your tempList... that way the tempList added to res keeps all the original references and is not changed by tempList.add() and tempList.remove()