Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList, List

Tags:

java

algorithm

When i am trying to solve subset problem, I write a code like that:

    public class Subsets {
        public List<List<Integer>> subsets(int[] nums) {
            List<List<Integer>> list = new ArrayList<>();
            Arrays.sort(nums);
            backtrack(list, new ArrayList<>(), nums, 0);
            return list;
        }
        public void backtrack(List<List<Integer>> list, ArrayList<Integer>temp, int[] nums, int start){
            list.add(temp);
            for(int i = start; i<nums.length;i++){
                temp.add(nums[i]);
                backtrack(list, temp, nums, i++);
                temp.remove(temp.size()-1);
            }        
        }
    }

The output is

[[],[],[],[],[],[],[],[]]

but the correct answer should be

[[3],[1],[2],[1,2,3],[1,3],[2,3],[1,2],[]]

When I change the "backtrack" code like that, the answer is correct:

public void backtrack(List<List<Integer>> list, List<Integer> temp, int[] nums, int start){
  list.add(new ArrayList(temp));
  for(int i = start; i<nums.length;i++){
   temp.add(nums[i]);
   backtrack(list, temp, nums, i+1);
   temp.remove(temp.size()-1);
   }
 }

My question: why do I need to write code like that:

    public void backtrack(List<List<Integer>> list, List<Integer> temp, int[] nums, int start){
        list.add(new ArrayList(temp));

instead of that:

    public void backtrack(List<List<Integer>> list, ArrayList<Integer> temp, int[] nums, int start){
        list.add(temp);
like image 551
AAMA Avatar asked Apr 16 '26 18:04

AAMA


1 Answers

Here:

list.add(new ArrayList(temp));

that creates a new List object, with the content of temp at this point of time.

Whereas

list.add(temp);

just adds a reference to the existing temp List to list.

So, in the second case, when you later modify temp that also affects the content of list.

But beyond that: you code is much harder to read/understand as it ought to be. There is no point in using a temp parameter to that method. You could make temp a local variable inside the method for example. The incoming list is empty anyway. You don't gain anything from making this an input parameter; you only add confusion.

And then you improve your naming - as list or temp really doesn't speak to the reader what the intend usages of these variables is.

like image 189
GhostCat Avatar answered Apr 19 '26 07:04

GhostCat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!