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

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

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

1.利用for或者while循环

#include<stdio.h>
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 %d\r\n",sum);
    }
    return 0;
    
}

2.利用递归算法

#include<stdio.h>
#include<malloc.h>
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("%d\r\n", 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次。

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

/*cout the time the plates will be moved
* n the number of the plates 
*/
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
/*A the source of the plates
B he transit of the plates
C tthe destination of the plates
*/
int hanioStep(int n,char A,char B,char C){
	if (n == 1) {
		printf("%c->%c\r\n",A,C);
	}
	else if (n <= 0) {
		return;
	}
	else {
		hanioStep(n - 1,A,C,B);
		printf("%c->%c\r\n",A,C);
		hanioStep(n - 1,B,A,C);
	}
}

测试函数

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

主函数

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

程序运行

 

 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值