Skip to content
Advertisement

instance variable difference (Python)

I have 2 questions about the solutions below.

Below is my answer (Solution 1) for this question of leetcode: https://leetcode.com/problems/distribute-coins-in-binary-tree/

JavaScript

Quesion1 I was wondering why below does not work. What is the difference between the variable ans of Solution 1 and Solution 2?

JavaScript

Because changes on grid variable below (Solution 3) is accumulated and affects all each recursions, I thought it would also be the case for Solution 2.

Question2 What is the difference between ans of Solution 2 and grid of Solution 3 which makes the differences due to recursion not accumulate? (Below is solution for https://leetcode.com/problems/number-of-islands/)

JavaScript

Advertisement

Answer

in solution #2 you pass integer ans to the dfs function, the function may change it but this change is not seen by the caller because integer is immutable so the modified ans is a new object that has nothing to do with the original ans=0.

On the other hand, Solution #3, pass List which is mutable object. Changing (mutating) this object grid[i][j] = '#' is seen to any scope that hold (reference to) this object.

This is the same as Solution #1 which change self.ans which is again the very same attribute of the very same object in all the recursion scopes.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement