栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

数据结构3.4递归算法——累加问题、汉诺塔问题

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

数据结构3.4递归算法——累加问题、汉诺塔问题

递归指的是,一个函数不断引用自身,直到引用的唯一已知对象时止的过程。

一、对于累加问题的处理,通常有两种解决方法

1.利用for或者while循环

#include
int main()
{
    int n;//add to n
    int i;//cyclic variable
    int sum=0;//total
    scanf_s("%d",&n);
    if(n<0){
        printf("false");
    }
    else{
        for(i=0;i<=n;i++){
            sum=sum+i;
        }
    printf("the total is %drn",sum);
    }
    return 0;
    
}

2.利用递归算法

#include
#include
int addTo(int n) {
	int sum;
	if (n <=0) {
	    return 0;
	}
	else {
		sum = addTo(n - 1) + n;
		return sum;
	}
}
int main() {
	int sum;
	sum = addTo(5);
	printf("%drn", sum);
}

二、汉诺塔问题

汉诺塔问题,一度难住了很多人,其实我们没有必要很细致的去追踪他的原理,只需要大致知道他的处理方式即可。汉诺塔问题主要需要解决的就是怎么挪和挪几次的问题,此处运用可以轻松解决。

首先,展开思路分析 A:resourse B:transit C:destination

将A上面的两个通过C移到B,之后再将A移到C,最后将B通过A移到C,具体为

黄色->C,粉色->B,黄色->B(完成将A上面的两个通过C移到B操作)

 蓝色->C,黄色->A,粉色->C,黄色->C(完成之后再将A移到C,最后将B通过A移到C操作)

一个盘子时,需要移动一次;两个盘子时,需要移动三次;三个盘子时,需要移动七次;以此类比推理,n个盘子,需要移动2*n+1次。

可以写出计算移动次数的函数

int hanioTimes(int n) {
	if (n == 1) {
		return 1;
	}
	else {
		return 2 * hanioTimes(n-1) + 1;
	}
}

 从case 3可以得出,一共有三种情况。第一种,将A上的前n-1个盘子通过C移动到B;第二种,将B上的通过A移动到C;第三种,直接将A上的第n个盘子移向C;

定义一个函数记录移动细节:int hanioStep(int n,char A,char B,char C)

//A位置:resourse B位置:transit C位置:destination

代码展示

//the detailed way to move the plates

int hanioStep(int n,char A,char B,char C){
	if (n == 1) {
		printf("%c->%crn",A,C);
	}
	else if (n <= 0) {
		return;
	}
	else {
		hanioStep(n - 1,A,C,B);
		printf("%c->%crn",A,C);
		hanioStep(n - 1,B,A,C);
	}
}

测试函数

void hShTTest() {
	printf("---test begin---rn");
	printf("1 platesrn");
	printf("the time you need to move is %d rn",hanioTimes(1));
	hanioStep(1, 'A', 'B', 'C');
	printf("2 platesrn");
	printf("the time you need to move is %d rn", hanioTimes(2));
	hanioStep(2, 'A', 'B', 'C');
	printf("3 platesrn");
	printf("the time you need to move is %d rn", hanioTimes(3));
	hanioStep(3, 'A', 'B', 'C');
	printf("4 platesrn");
	printf("the time you need to move is %d rn", hanioTimes(4));
	hanioStep(4, 'A', 'B', 'C');
	printf("---Test end---rn");
}

主函数

int main() {
	hShTTest();
	return 0;
}

程序运行

 

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/878930.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号