2

I was just wondering whether if it was possible to replace recursion with an explicit stack when you need the return value(s) and are comparing them to find the best solution (like dynamic programming)?

So something like (it doesn't do anything, just an example):

int resursiveFunction (int state) { 

   if (known[state]) return cache[state];
   if (state == MAX_STATE) return 0;

   int max = 0;

   for (int i = 0 ; i < 5; i++) {
      int points = curPoints (state) + recursiveFunction (state+i);
      if (points > max) max = points; 
   }

   known[state] = true;
   cache[state] = max;
   return max; 

}

0

1 Answer 1

3

Yes. It's possible.

Simply push and pop as appropriate. Recursion simply creates an 'implicit stack'. You can unwind TCO'able recursive functions as well.

You may find Stacks and Recursion Elimination (it's for a course) useful. It covers elimination (left-recursive) as well as emulation (stack).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! This is what I needed. "Returning" was what I was confused about.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.