递归算法
本文最后更新于230 天前,其中的信息可能已经过时,如有错误请发送邮件到qiqin-chang@qq.com

全排序:

import java.util.LinkedList;
import java.util.Scanner;
​
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String[] arr = sc.nextLine().split(" ");
        LinkedList<String> list = new LinkedList<>();
        dfs(arr,list);
    }
    
    public static void dfs(String[] arr,LinkedList<String> list) {
        if(list.size()>=arr.length){
            System.out.println(list);
            return;
        }
        for(int i=0;i<arr.length;i++){
            if(!list.contains(arr[i])){
                list.add(arr[i]);
                dfs(arr,list);
                list.removeLast();
            }
        }
    }    
}

斐波那契数列:

import java.util.Scanner;
​
//斐波那契数列
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
​
        System.out.println(fb(n));
    }
​
    static int fb(int n) {
        if(n == 1||n == 2){
            return 1;
        }
        return fb(n-1) + fb(n-2);
    }
}

汉诺塔:

import java.util.Scanner;
​
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
​
        int n = sc.nextInt();
        printHanoiTower(n,"A","B","C");
​
    }
​
    static void printHanoiTower(int n,String from,String to,String help) {
        if(n==1) {
            System.out.println(n+":"+from+"->"+to);
        }else{
            printHanoiTower(n-1,from,help,to);  //将前N-1个盘子移至辅助空间
            System.out.println(n+":"+from+"->"+to);
            printHanoiTower(n-1,help,to,from);  //将N-1个盘子从辅助空间移回源空间
        }
    }
}
暂无评论

发送评论 编辑评论


|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇