递归算法-小例子


import java.util.ArrayList;
import java.util.List;

public class digui {
    private static int a = 3;
    private static int count = 0;

    public static void yd(int n, String from, String mid, String to) {
        // a(起始值) b c(目标)
        if (n == 1) {
            System.out.println(n + "从" + from + " 移动到 " + to);
        } else {
            yd(n - 1, from, to, mid);
            // move(n,from,to);
            System.out.println(n + "从" + from + " 移动到 " + to);
            yd(n - 1, mid, from, to);
        }
    }

    public static void move(int x, String from, String to) {
        System.out.println(x + "从" + from + " 移动到 " + to);
    }

    public static void qpl(List<Integer> list, int s, int e) {
        if (s >= e) {
            count++;
            System.out.println(count + "   " + list.toString());
        } else {
            for (int i = s; i < e; i++) {
                swap(list, s, i);// 将当前索引为i的值与起始索引s的值进行交换
                qpl(list, s + 1, e);// 将i=i+1...e的数字进行全排列
                swap(list, i, s);// 将之前的交换操作撤回(恢复数据),方便下次全排列使用
            }
        }
    }

    public static void swap(List<Integer> l, int i, int j) {
        int tmp = l.get(i);
        l.set(i, l.get(j));
        l.set(j, tmp);
    }
    
    public static void fb(int n){
        int f1=1;
        int f2=1;
        int i=0;
        while(i<=n){
            f2=f1+f2;
            f1=f2-f1;//保留f1的值,留着下次使用
            System.out.print(" ,"+f2);
            i++;
        }
    }
    
    public static int fb1(int n){
        int i=0;
        if(n<2){
            return 1;
        }else{
            int x=fb1(n-1)+fb1(n-2);
            return x;
        }
    }

    public static void main(String[] args) {
        yd(a, "a", "b", "c");// 将a个盘子从a柱借助b柱移动到c柱。
        List<Integer> l = new ArrayList<Integer>();
        l.add(1);
        l.add(2);
        l.add(3);
        l.add(4);
        qpl(l,0,l.size());//全排列
        for(int i=0;i<10;i++){
        System.out.print(fb1(i)+",");//递归生成1 1 2 3 5 8 ...
        }
        System.out.println();
        fb(6);//非递归
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值