递归函数

73 阅读1分钟

递归函数:自己调用自己的函数

object Base44 {
    //定义函数
    def f():Unit = {
      println("f.....被调用了")
      f()//调用函数
    }
  def main(args: Array[String]): Unit = {
    f()
    println("over")
  }
}

修改代码,完成阶乘的功能

object Base45 {
  /*
  1 可以被分解为类似子问题
  2 当分解到足够小的时候,问题可以直接求解
   */
  //阶乘 n!=1*2*3*...*n
    def f(n:Int):Int = {
      if(n == 1)
        1
      else
        f(n-1) + n
    }
  def main(args: Array[String]): Unit = {
    var rst = f(4)
    println(rst)
  }
}

用斐波那契数列求f(10)的值

object Base46 {
  /*
  1 可以被分解为类似子问题
  2 当分解到足够小的时候,问题可以直接求解
   */
  //斐波那契数列
    def f(n:Int):Int = {
      if(n == 1)
        1
      else if(n==2) {
        2
      }else {
        f(n-1) + f(n-2)
      }
    }
  def main(args: Array[String]): Unit = {
    var rst = f(10)
    println(rst)
  }
}
object Base47 {
  //把输入的整数的各个位数上的数值输出来
  def f(n:Int):Unit = {
    if(n<9){
      println(n)
    }else {
      f(n/10)
      println(n%10)
    }
  }
  def main(args: Array[String]): Unit = {
    f(12)//1 2 3 4 5
  }
}

汉诺塔

object Base48 {
  //把输入的整数的各个位数上的数值输出来
  def f(n:Int,A:Char,B:Char,C:Char):Unit = {
    if(n==1){
      println(s"${A} ---> ${C}")
    }else {
      f(n-1,A,C,B)
      println(s"${A} ---> ${C}")
      f(n-1,B,A,C)
    }
  }
  def main(args: Array[String]): Unit = {
    f(4,'A','B','C')
  }
}