JAVA 幾個遞歸算法實例


1、求1-n的和

public static int getSum(int n) {
        if(n == 1) 
            return 1;
        return n+getSum(n-1);
    }
    
    public static void main(String[] args){
        System.out.println(getSum(100));
        //5050
    }

2、輸出斐波那契數列

public static int getFibonacci(int n) {
        if(n==1)
            return 1;
        if(n==2)
            return 1;
        return getFibonacci(n-1)+getFibonacci(n-2);
    }
    
    public static void main(String[] args){
        for(int i = 1;i<=10;i++) {
            System.out.print(getFibonacci(i)+" ");
        }
//1 1 2 3 5 8 13 21 34 55 }

3、遍歷二叉樹(讓用戶輸入數據,並排序輸出)

class Node {
    int value;
    Node left;
    Node right;
    Node(int input){
        value = input;
    }
}

public class Main {
    
    
    
    public static void put(Node node,int number) {
        if(number<=node.value) {
            if(node.left == null) {
                node.left = new Node(number);
            }else {
                put(node.left,number);
            }
        }else {
            if(node.right == null) {
                node.right = new Node(number);
            }else {
                put(node.right,number);
            }
        }
    }
    
    public static void showasc(Node node) {
        if(node.left!=null) {
            showasc(node.left);
        }
        System.out.print(node.value+" ");
        if(node.right!=null) {
            showasc(node.right);
        }
    }
    public static void showdesc(Node node) {
        if(node.right!=null) {
            showdesc(node.right);
        }
        
        System.out.print(node.value+" ");
        
        if(node.left!=null) {
            showdesc(node.left);
        }
    }
    
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        
        System.out.println("您希望存幾個數?");
        int count = sc.nextInt();
        
        System.out.println("請輸入第1個數:");
        Node root = new Node(sc.nextInt());
        
        for(int i = 2;i<=count;i++) {
            System.out.println("請輸入第"+i+"個數:");
            int number = sc.nextInt();
            put(root,number);
        }
        
        System.out.println("從小到大排序為:");
        showasc(root);
        System.out.println("\n從大到小排序為:");
        showdesc(root);
    }
}

運行結果:

您希望存幾個數?
6
請輸入第1個數:
6
請輸入第2個數:
1
請輸入第3個數:
5
請輸入第4個數:
2
請輸入第5個數:
4
請輸入第6個數:
3
從小到大排序為:
1 2 3 4 5 6
從大到小排序為:
6 5 4 3 2 1

4.獲取文件目錄下的所有文件夾和文件

文件目錄如圖所示:

 

 

public static void show(File f) {
        for(File fs:f.listFiles()) {
            if(fs.isFile()) {
                System.out.println(fs);
            }
            if(fs.isDirectory()) {
                show(fs);
            }
        }
    }
    
    public static void main(String[] args){
        File f = new File("D:\\Recursion");
        show(f);
    }

運行結果:

D:\Recursion\Documents\Document1.pdf
D:\Recursion\Documents\Document2.ppt
D:\Recursion\Documents\Document3.doc
D:\Recursion\Photos\Photo1.jpg
D:\Recursion\Photos\Photo2.bmp
D:\Recursion\ReadMe.txt
D:\Recursion\Videos\Video1.mp4
D:\Recursion\Videos\Video2.avi

 5.漢諾艾塔解法演示

Hanoi類:

import java.util.Stack;

public class Hanoi {
    int layers = 3;
    
    //代表漢諾埃塔的三個槽
    Stack<Integer> A = new Stack<>();
    Stack<Integer> B = new Stack<>();
    Stack<Integer> C = new Stack<>();
    
    //定義展示矩陣
    int[][] hanoi_matrix = null;
    
    Hanoi(int layers){
        //高度不能小於1
        if(layers<1)
            this.layers = 1;
        else
            this.layers = layers;
        
        //初始化展示矩陣
        hanoi_matrix = new int[layers][3];
        
        for(int[] row :hanoi_matrix) {
            for(int col:row) {
                col = 0;
            }
        }
        //將n個盤插入a柱中
        for(int i =0;i<layers;i++) {
            A.push(layers-i);
        }

    }
    //打印hanoi塔
    public void showHanoi() {
        
        //將展示矩陣清空
        for(int i = 0;i<hanoi_matrix.length;i++) {
            for(int j = 0;j<hanoi_matrix[i].length;j++) {
                hanoi_matrix[i][j] = 0;
            }
        }
        
        
        //將目前各柱的盤情況映射到展示矩陣上
        
        for(int i = 0;i<A.size();i++) {
            hanoi_matrix[layers-i-1][0]=A.get(i);
        }
        for(int i = 0;i<B.size();i++) {
            hanoi_matrix[layers-i-1][1]=B.get(i);
        }
        for(int i = 0;i<C.size();i++) {
            hanoi_matrix[layers-i-1][2]=C.get(i);
        }
        
        
        //按照最合適大小打印hanoi塔
        for(int[] row :hanoi_matrix) {
            for(int radius:row) {
                for(int i = 0;i<(layers-radius);i++) {
                    System.out.print(" ");
                }
                for(int i = 0;i<radius;i++) {
                    System.out.print("=");
                }
                System.out.print("|");
                for(int i = 0;i<radius;i++) {
                    System.out.print("=");
                }
                for(int i = 0;i<(layers-radius);i++) {
                    System.out.print(" ");
                }
                System.out.print("  ");
            }
            System.out.println();
        }
        
    }
    //將某柱上最上面一個盤移動到另一個柱上
    public void movetop(char from,char to) {
        //停頓一下便於觀察
        try {
            Thread.sleep(1500);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Main.count++;
        System.out.print("第"+Main.count+"次移動:");
        System.out.println("將"+from +"柱頂端的盤移動到"+to+"柱上:");
        
        //將源柱彈棧
        int d = 0;
        switch(from) {
        case 'a':
            d = A.pop();
            break;
        case 'b':
            d = B.pop();
            break;
        case 'c':
            d = C.pop();
            break;
        }
        //目標柱壓棧
        switch(to) {
        case 'a':
            A.push(d);
            break;
        case 'b':
            B.push(d);
            break;
        case 'c':
            C.push(d);
            break;
        }
        showHanoi();
    }
    
}

測試類:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        System.out.println("請輸入您希望演示的層數:");
        int layers = new Scanner(System.in).nextInt();
        Hanoi h = new Hanoi(layers);
        System.out.println("原始:");
        h.showHanoi();
        move(h,layers,'a','c','b');
        System.out.println("移動完成!");
        
    }
    static int count = 0;
    //移動  傳入Hanoi塔對象,想要要移動的層數,源柱,目標柱,輔助柱
    public static void move(Hanoi h,int layers,char from,char to,char by) {
        if(layers == 1) {
            //如果塔只有一層,直接移過去即可
            h.movetop(from, to);
        }else {
            //如果大於一層,最大層上面的n-1層看成一個整體,先移到輔助柱
            move(h,layers-1,from,by,to);
            //將最大的盤移到目標柱
            h.movetop(from, to);
            //將輔助柱上的盤移到目標柱上
            move(h,layers-1,by,to,from);
        }
    }
}

效果演示:

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM