Several classical recursion problems

Following from Wikipedia:
recursion (English: Recursion ), also translated handed back in Mathematics and Computer Science , the method refers to the use of the function itself defined function. The term is frequently used to further recursive self-similar procedure described process is repeated things. For example, when approximately parallel to each other between the two mirrors, the mirror image in the form of nested occurring infinite recursion. It can also be understood as a process of self-replication.
A few examples will help to understand recursion Wikipedia :

  1. There was once a mountain, the mountain there was a temple, the temple has an old monk, the young monk is to tell stories to tell! What story is it? "There was once a mountain, the mountain there was a temple, the temple has an old monk, the young monk is to tell stories to tell! What story is it? 'There was once a mountain, the mountain there was a temple, the temple has an old monk, is to tell the story of the young monk it! What story is it? ...... ' "
  2. A dog came into the kitchen and stole a small piece of bread. Cook lifted ladle, the dog killed. Then all the dogs came running, give the dog dug a grave, is still engraved epitaph on the tombstone, so the dog can see the future: "A dog came into the kitchen and stole a small piece of bread. cook lifted ladle, the dog then killed all the dogs came running, give the dog dug a grave, is still engraved epitaph on the tombstone, so the dog can see the future: 'a dogs came to the kitchen and stole a small piece of bread. cook lifted ladle, the dog is dead. then all the dogs came running, give the dog dug a grave, also carved on the tombstone epitaph, let the dog can see the future ...... ' "
  3. Nobita in the room, looking at the future situation with time television. At that time the television screen, he is using time television, watching the future situation. At that time the TV screen of the TV screen, he is using time television, watching the future situation ......

Recursive two points
1. recursive group: Under special circumstances, the general recursive outlet.
2. recursive expression: that part of double counting.

A. Factorial
mathematical expression
n ! = n ( n 1 ) ( n 2 ) 2 1 n! = n\cdot (n-1)\cdot (n-2)\cdot \cdot \cdot 2\cdot 1
can easily write recursive code

 public static int fact(int n) {
        if (n <= 1)
            return 1;
        return n * fact(n - 1);
    }

II. Seeking Fibonacci columns
have mathematical expression
f ( n ) = { 1 , n = 1 1 , n = 2 f ( n 1 ) + f ( n 2 ) , n > 2 f(n)= \left\{ \begin{aligned} 1 &&, n=1\\ 1&&, n=2\\ f(n-1)+f(n-2)&&,n>2\\ \end{aligned} \right. It makes it easy to write a recursive code

public static int fib(int n) {
        if (n == 1 || n == 2) {
            return 1;
        }
        return fib(n - 1) + fib(n - 2);
    }

III. Summing array
which may be viewed as a recursive problem, the required number n of the array and may be converted into start and the first number and the number of the remaining n-1 and.

  • Base case: the beginning of the last number of the array, will return that number.
  • Recursion: the beginning and the first number and the remaining number n-1.
 /**
   * 数组求和
   * @param arr   -数组
   * @param begin -数组起始位置
   * @return
   */
 public static int sum(int[] arr, int begin) {
        if (begin == arr.length - 1)
            return arr[begin];
        else if (begin >= arr.length) {
            throw new ArrayIndexOutOfBoundsException("数组下标越界……");
        } else {
            return arr[begin] + sum(arr, begin + 1);
        }
    }

IV. Reverse string

  • Recursive analysis: to break the problem into reverse last character with the rest of the string.
  • Base case: only one character is returned directly characters
  • Recursive: Solving the last remaining character string
/**
  * 字符串反转
  * @param src  -原字符串
  * @param end  -最后一个字符
  * @return 反转后的字符串
  */
    public static String reverse(String src, int end) {
        if (end == 0) {
            return src.toCharArray()[end] + "";
        }
        return src.toCharArray()[end] + reverse(src, end - 1);
    }

V. greatest common divisor
which is a mathematical problem using the Euclidean algorithm.

  • Euclidean algorithm based on the principle: the greatest common divisor of two integers is equal to the smaller number of the greatest common divisor and dividing the two remainder. For example, the greatest common divisor of 252 and 105 is 21 (252 = 21 × 12; 105 = 21 × 5); as 252 - 105 = 21 × (12 - 5) = 147, 147 and 105 so that the greatest common divisor is 21 . In this process, a large number of so reduced that the same calculation can be continued shrinking until one of these two numbers to zero. At this time, the remaining number has not yet become zero is the greatest common divisor of two numbers.

  • Base case: two numbers one to zero.

  • Recursion: Find the greatest common divisor number and a smaller number of larger and smaller number of remainder

/**
  * 最大公约数
   * @param m
   * @param n
   * @return
   */
    public static int gcd(int m, int n) {
        if (n == 0) {
            return m;
        }
        return gcd(n, m % n);
    }

VI. Insertion Sort recursion

 /**
   * 插入排序递归法
   * @param arr -数组
   * @param k  -数组前k个元素
   */
    public static void insertionSort(int arr[],int k){
        if(k==0)
            return;
        insertionSort(arr,k-1);
        int tmp = arr[k];
        int i = k - 1;
        while(i>=0 && arr[i]>=tmp){
            arr[i+1]=arr[i];
            --i;
        }
        arr[i+1] = tmp;
    }

VII. Tower of Hanoi problem

public static void printHanoTower(int n,String from,String to, String help){
        if(n==1){
            System.out.println("move "+n+" from "+from+" to " + to);
            return;
        }
        printHanoTower(n-1,from,help,to);
        System.out.println("move "+n+" from "+ from +" to "+to);
        printHanoTower(n-1,help,to, from);
    }
Published 13 original articles · won praise 5 · Views 684

Guess you like

Origin blog.csdn.net/qq_43657590/article/details/103946933