1.基本情况:直接能求的。
2.递归情况。
求汉罗塔游戏的步骤
//记:f(,"A","B","C")表示把n个盘子从A柱子上移动到C柱子上,借用B柱子的过程
//1.基本情况(直接能求的):f(1,"A","B","C"),可以直接求 直接从A到C
//2.递归情况:f(n)=f(n,"A","B","C")=
def han(n:Int,A:String,B:String,C:String): Unit ={
if(n ==1){
println(s"$A ---->$C")//直接从A到C
}else{
han(n-1,A,C,B)//A到B借助C
println(s"$A----->$C") //最底下的就是直接从A到C
han(n-1,B,A,C)//B到C借助A
}
}
def main(args: Array[String]): Unit = {
han(3,"A","B","C")
}
def main(args: Array[String]): Unit = {
val a = sum1(4, 5)
println(s"a=$a")
val a2 = sum2(4, 5)
println(s"a2=$a2")
println(s"gcd=${gcd(0, 4)}")
}
//1.
def sum1(x: Int, y: Int): Int = {
return x + y
}
def sum2(x: Int, y: Int): Int = return x + y
//2.
def gcd(x: Int, y: Int): Int = {
if(x==0) y
else gcd(y%x,x)
}
}