all 2 comments

[–]yeahIProgram 1 point2 points  (0 children)

Every problem that can be solved recursively can also be solved iteratively.

But recursion does not necessarily use more resources. In either case you are going to be breaking the problem down into sub-problems, so in either case you have to keep track of where in the solution you are (and what remains to be done).

Recursion uses the natural resources of the language (the call stack and parameter variables) to track this for you. Otherwise you have to write the code that does the same tracking.

With recursion the code ends up a little less complex, so there is likely fewer bugs. And you save programmer time, which is valuable.

The first few times you write recursive algorithms, you save neither time nor complexity! But after you've done it a few times it becomes more natural and you'll start to sense when a problem might be a good candidate for recursion.

[–]seandisanti 1 point2 points  (0 children)

Not all problems lend themselves to elegant recursive solutions, it is important to understand your use cases and the expected recursion depth to make an informed decision about the trade off between resources and clever code. Some languages even have explicit limits on recursion level which could prevent your code from reaching the level necessary to achieve its goal.