4.16 Recursion

3 阅读1分钟

1. Exam Points

  • Predict results of recursion based on a given scenario.
  • Analyze the behavior of a given recursive code segment.

2. Knowledge Points

(1) Recursion

  • A recursive method is a method that calls itself.
  • Recursive methods contain at least one base case, which halts the recursion, and at least one recursive call.
  • Recursion is another form of repetition.
  • Any recursive solution can be replicated through the use of an iterative approach and vice versa.

(2) Examples

  • Example 1: print before recursion : first print and then do recursion.
    public static void printSth(int n) {
    	
        if (n > 3) { // the condition to halt recursion
            return;
        }
    
        // here print is before recursion, so first print and then do recursion
        System.out.print(n + " "); 
        printSth(n + 1); // recursion
    }
    
    public static void main(String[] args) {
        printSth(1);
    }
    
    • Analysis:
      • how n changes: 1 2 3 4
      • when print is executed: n = 1, 2, 3 (when n is 4, return, no printing)
      • Print result: 1 2 3
      • Process:
        image.png
  • Example 2: print after recursion : first do recursion and then print when recursion is done, so printing is done reversely.
    public static void printSth(int n) {
    	
        if (n > 3) { // the condition to halt recursion
            return;
        }
    
        printSth(n + 1); // recursion
        
        // here print is after recursion, so first do recursion and print after recursion is done
        System.out.print(n + " "); 
    }
    
    public static void main(String[] args) {
        printSth(1);
    }
    
    • Analysis:
      • how n changes: 1 2 3 4
      • when print is executed: n = 1, 2, 3 (when n is 4, return, no printing)
      • Print result: 3 2 1
      • Process:
        image.png
  • Example 3: multiple recursion in a method.
    public static int recur(int n) {
    
        if (n <= 1) {
            return 1;
        } else {
            return (recur(n - 2) + recur(n - 1));
        }
    }
    
    public static void main(String[] args) {
        // predict output
        System.out.println(recur(4));
    }
    
    • Analysis:
      • recur(4) -> recur(2) + recur(3)
      • recur(2) -> recur(0) + recur(1) = 1 + 1 = 2
      • recur(3) -> recur(1) + recur(2) = 1 + 2 = 3
      • so, recur(4) = recur(2) + recur(3) = 2 + 3 = 5

3. Exercises