Fibonacci and Tower of Hanoi in the basic algorithm series

The Fibonacci sequence (Fibonacci sequence), also known as the golden section sequence, was introduced by the mathematician Leonardo Fibonacci (Leonardoda Fibonacci) using rabbit reproduction as an example, so it is also called the "Rabbit Sequence", referring to Is a series of numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
Tower of Hanoi (Tower of Hanoi), also known as the Tower of Hanoi, is derived from ancient Indian legends brain game. On a pillar, 64 golden discs are stacked in order of size from bottom to top, and the discs need to be re-placed on another pillar in order of size from the bottom. It is also stipulated that the disc cannot be enlarged on the small disc, and only one disc can be moved between the three pillars at a time.
The code is as follows:

public class Fibonacci{
    
    
	public static int fibonacci(int i){
    
    
		if(i==1 || i==2){
    
    		//递归问题一定要有终止条件
			return 1;
		}else{
    
    
			return fibonacci(i-1)+fibonacci(i-2);
		}
	}
}

public class Hanoi{
    
    
	public static void hanoi(int n,char from,char temp,char to){
    
    
		if(n==1){
    
    
			System.out.println("第一个盘子从"+from+"到"+to+";");
		}else{
    
    
			hanoi(n-1,from,to,temp);	//移动上面的盘子
			//移动下面的盘子
			System.out.println("第n个盘子从"+from+"到"+to+";");
			//上面的盘子从中间移到目标
			hanoi(n-1,temp,from,to); //移动上面的盘子
		}
	}
}

Guess you like

Origin blog.csdn.net/langxiaolin/article/details/113470372