TypeScript数据结构与算法(9)递归-Recursion-汉诺塔问题
了解递归,掌握递归,对于学习更高级的数据结构是必须要的。什么是递归,递归的性质:
1.自己调用自己
2.存在结束条件
只有满足以上两点,这个递归才算是合法的递归,递归的代码:
test1(x) { console.log(x);//没有结束条件,死递归 this.test1(x - 1); } test2(x){ if(x>0){ //存在正确的结束条件,合法递归 console.log(x); this.test2(x-1); } } test3(x){ if(x>0){//存在错误的结束条件,死递归 console.log(x); this.test3(x+1); } } test4(x){ if(x>0){//存在正确的结束条件,合法递归 this.test4(x-1); console.log(x); } }
汉诺塔示意图
问题描述:
1.将A柱子上的盘子,按照原样的摆放顺序放到另外一根柱子上
2.在移动过程中,小圆片上面不能放大圆片,在三根柱子之间一次只能移动一个圆片
代码实现:
/** * Autor: Created by 李清风 on 2020-12-11. * Desc: 递归操作(解决汉诺塔问题,自行百度搜索描述),关键词:调用自身,结束条件 */ export class DataStruct_RecursionHanoi { //n:n个盘子,a,b,c三个柱子 Hanoi(n: number, a: string, b: string, c: string) { if (n > 0) { //解题步骤 //1.把n-1个盘子,从a经过c移动到b //2.把第n个盘子从a移动到c //3.把n-1个盘子从b经过a移动到c this.Hanoi(n - 1, a, c, b); // 将n-1个盘子从a经过c,移动到b console.log(`moving from ${a} to ${c}`); this.Hanoi(n - 1, b, a, c); } } }