forum

Home / DeveloperSection / Forums / Change parameter handled during recursion in Java

Change parameter handled during recursion in Java

Anonymous User167904-Nov-2014
Here is a recursive method:
privatestaticint minimumTotal(List<List<Integer>> triangle,int index){if(triangle.isEmpty()){return0;}List<Integer> row = triangle.remove(0);int sum1 = row.get(index)+ minimumTotal(triangle, index);int sum2 = row.get(index)+ minimumTotal(triangle, index +1);returnMath.min(sum1, sum2);}

I want sum1 and sum2 to be calculated on the same triangle object. However, what happens is the following: after sum1 is calculated, one row of a triangle (and then another within the recursion and another ...). Now, when sum2 has calculated it has a triangle that is empty!

1.  This confuses me regarding how Java handles recursion. Why is the object triangle getting modified? I was under the assumption that it should be a "local" data at every recursion level.

2.  How can we rewrite the code to get the desired behavior?


Updated on 04-Nov-2014
I am a content writter !

Can you answer this question?


Answer

1 Answers

Liked By