Recursive basic exercises (part 2)

Novice Diary-January 23

Case number one:

Multi-branch recursion, Fibonacci sequence

Use code to find the value of a certain Fibonacci sequence

Fibonacci sequence: The value of this term is equal to the sum of the first two terms
such as: 1,1,2,3,5,8,13...

分解成两个子问题,f5(n-1)和f5(n-2)
static int f5(int n){
    
    
        if (n == 1 || n == 2){
    
    
            return 1;
        }
        return f5(n - 1) + f5(n - 2);
    }

Effect picture:
Insert picture description here
Insert picture description here
Case 2:

Find the greatest common divisor

m continues to take the remainder of n, until n=0,
default m> n

static int f6(int m,int n){
    
    
        if (n == 0){
    
    
            return m;
        }
        return f6(n,m % n);
    }

Effect picture:
Insert picture description here
Insert picture description here
Case three:

Insertion sort

static void f7(int[] array,int k){
    
    
        if (k == 0){
    
    
            return;
        }
        int x = array[k];
        int index = k - 1;
        f7(array,k-1);
        while (x < array[index] && index > -1){
    
    
            array[index + 1] = array[index];
            index--;
        }
        array[index + 1] = x;
    }

Case Four:

Print the travel path of the Tower of Hanoi

Insert picture description here

static void printHanoiTower(int N,String from,String to,String help){
    
    
        if (N == 1){
    
    
            System.out.println("移动  " + N + "号盘子  " + from + " --> " + to);
            return;
        }
        //将1 ~ N-1个盘子从A柱移动到C柱,B作为辅助柱子(这里的移动并不是指直接移动)
        printHanoiTower(N - 1,from,help,to);
        //打印将N号盘子从A柱移动到B柱
        System.out.println("移动  " + N + "号盘子  " + from + " --> " + to);
        //将1 ~ N-1个柱子从C柱移动到B柱,A作为辅助柱子
        // (B柱此时放的柱子N最大,可以继续放任意柱子,所以可以视为空)
        printHanoiTower(N - 1,help,to,from);
    }
}

Effect picture:
Insert picture description here

Guess you like

Origin blog.csdn.net/ghl971/article/details/113060954