简体   繁体   中英

Stuck with understanding recursion

For the past couple of hours, I have tried to understand why the output for this program is behaving in such a weird manner. The first part of the recursive functions makes sense to me, however, the rest I, unfortunately, find extremely confusing.

I was wondering how come that the program is going backward, and even adds to a variable that should be subtracted instead. This does not make any sense to me. I would appreciate any help, thanks.

Here is my recursive function:

public static void threeWays(int id, int n) {
    if (n >= 0) {
        System.out.println(id + "=" + n);
        threeWays(id + 1, n - 1);
        threeWays(id + 1, n - 2);
        threeWays(id + 1, n - 3);
    }
}

public static void main(String[] args) {
    threeWays(1, 4);
}

And here's the output:

1=4

2=3

3=2

4=1

5=0

4=0

3=1

4=0

3=0

2=2

3=1

4=0

3=0

2=1

3=0

Python3 version:

  def threeWays(f, i, n):
      if n >= 0:
          print(f, i, '=', n)
          threeWays('1st', i + 1, n - 1)
          threeWays('2nd', i + 1, n - 2)
          threeWays('3rd', i + 1, n - 3)

  threeWays('    ', 1, 4)

At the first sight, it could, could look like DFS but actually not...

When threeWays is recursively called from 2nd and 3rd threeWays , 1st or 1st and 2nd threeWay (s) is/are also called...!

threeWays('   ', 1, 4)            ->     1 = 4
  threeWays('1st', 2, 3)          -> 1st 2 = 3
    threeWays('1st', 3, 2)        -> 1st 3 = 2
      threeWays('1st', 4, 1)      -> 1st 4 = 1
        threeWays('1st', 5, 0)    -> 1st 5 = 0
          threeWays('1st', 6, -1)
        threeWays('2nd', 5, -2)
        threeWays('3rd', 5, -3)
      threeWays('2nd', 4, 0)      -> 2nd 4 = 0
      threeWays('3rd', 4, -1)
    threeWays('2nd', 3, 1)        -> 2nd 3 = 1
      threeWays('1st', 4, 0)      -> 1st 4 = 0
      threeWays('2nd', 4, -1)
      threeWays('3rd', 4, -2)
    threeWays('3rd', 3, 0)        -> 3rd 3 = 0
...

You might find it more useful if you indent the output to show how deep the call stack is at each point. I replaced your print statement with System.out.println(" ".repeat(id) + n);and received the output:

  4
    3
      2
        1
          0
        0
      1
        0
      0
    2
      1
        0
      0
    1
      0

The structure here is that every time a number is printed, the next level shows the three numbers below in descending order, until it gets to zero. That is exactly what your function does.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM