zoukankan      html  css  js  c++  java
  • fib函数用迭代替换递归

    fib函数递归实现:

            long Fib(long n) 
    {
    if (n <= 1)
    {
    return n;
    }
    else
    {
    var t1 = Fib(n - 1);
    var t2 = Fib(n - 2);

    return t1+ t2;
    }

    }

    fib函数改为迭代:

        class Class1
    {
    class Node
    {
    public Node(long n, int pos)
    {
    this.n = n;
    this.retStatus = pos;
    }

    public long n; //参数
    public int retStatus;
    //0,表示temp中没有保存值
    //1, 表示temp中保存了栈顶记录的t1值。
    //2,表示temp中保存了栈顶记录的t2值。

    public long ret; //返回值
    public long t1; //存第一次调用Fib的返回值
    public long t2; //存第二次调用Fib的返回值
    }

    long Fib(int n)
    {
    long temp = 0;

    var s = new Stack<Node>();
    s.Push(new Node(n, 0));

    while (s.Count > 0)
    {
    Node top = s.Peek();

    switch (top.retStatus)
    {
    case 0:
    if (n <= 1)
    {
    top.ret = n;
    temp = top.ret;
    s.Pop();
    }
    else
    {
    top.retStatus = 1;
    s.Push(new Node(n - 1, 0));
    }
    break;
    case 1:
    top.t1 = temp;

    top.retStatus = 2;
    s.Push(new Node(n - 2, 0));
    break;
    case 2:
    top.t2 = temp;

    top.ret = top.t1 + top.t2;
    temp = top.ret;
    s.Pop();
    break;
    }

    }
    return temp;

    }

    }



  • 相关阅读:
    S3C2440实现dm9000网卡驱动程序移植
    IMX257虚拟网卡vnet驱动程序
    ram_flash驱动
    S3C2440 nor_flash驱动程序
    Java 打印* 三角形
    Java系列学习说明
    java案例1,打印hello java
    zabbixproxy安装
    python鉴黄程序
    mssql发布订阅事项
  • 原文地址:https://www.cnblogs.com/cuishengli/p/2377714.html
Copyright © 2011-2022 走看看