is there ever a time you would not use recursion?

Yes, there are plenty of times I would not use recursion. Recursion is not free, it has a cost in stack space and that can often be a much more limited resource than some others. There's also a time cost, however small, in setting up and tearing down stack frames.

By way of example, the much vaunted factorial function is one where I would probably opt for an iterative approach where the numbers were large. Calculating 10000! with (this looks like Python but that's only because Python is a really nice pseudo-code language):

def factorial (n):
    if n = 1 return 1
    return n * factorial (n-1)

will use 10,000 stack frames (assuming it's not optimised by the compiler into an iterative solution of course), quite a lot. The iterative solution:

def factorial (n):
    r = 1
    while n > 1:
        r = r * n
        n = n - 1
    return r

will use just the one stack frame and precious little else.

It's true that recursive solutions are often more elegant code but you have to temper that with the limitations of your environment.

Your carbon example is one where I would actually use recursion since:

  • it uses at most six stack frames (one per character in the string); and
  • it's relatively elegant, at least much more so than six nested loops and huge equality checks.

For example the following Python code does the trick:

def recur (str, pref = ""):
    # Terminating condition.

    if str == "":
        print pref
        return

    # Rotate string so all letters get a chance to be first.

    for i in range (len (str)):
        recur (str[1:], pref + str[:1])
        str = str[1:] + str[:1]

recur ("abc")

producing:

abc
acb
bca
bac
cab
cba

Of course, if your string can be 10K long, I'd rethink it, since that would involve a lot more stack levels but, provided you keep in low enough, recursion is a viable solution.


Use recursion when your data is inherently hierarchical/nested. Use iteration when your data is linear/flat.

In your case, there is a natural ordering you can impose on the combinations, so you can treat the data as linear, but if you view it as a tree you end up with the recursive approach.

If the structure of your algorithm reflects the structure of the underlying problem, you end up with simpler code that is easier to understand. Don't use recursion just because your CS201 professor thought it was So! Cool!


Just use a loop and you will avoid using recursion. Recursion is avoided generally because it makes the code less readable and harder to maintain and debug. If you have low resources as paxdiablo said stack space might be valuable for you so you should avoid using it then too.

Tags:

Java

Recursion