算法-Hanoi塔问题+递归
2017-12-20 12:54
399 查看
N阶Hanoi塔问题
要求:(1) 采用分治策略,写出相应问题的递归算法及程序,(2)要求输出整个搬动过程。/* 递归演示汉诺塔移动过程(设最上面的一个盘子为第1个盘子) */ include<stdio.h> //Show the movement of the n-th plate void move(int n, int x, int y){ printf("the %dth plate from %c to %c\n",n,x+65,y+65); } //将n个盘子从A座移到C座的过程(借助B座) void hanoi(int n, int A, int B, int C){ if(n==1) move(n,A,C); else{ hanoi(n-1,A,C,B); move(n,A,C); hanoi(n-1,B,A,C); } } //The main function int main() { int n; //Hanoi's total plates printf("Assuming the top plate is the first plate\nplease input the number of plate : "); scanf("%d",&n); hanoi(n,0,1,2); }
找出n个自然数(1,2,3,…,n)中取r个数的组合。
要求:(1)采用分治策略,写出相应问题的递归算法及程序(2)要求输出所有的r个数的组合。递归实现
#include<iostream> using namespace std; int a[100]; comb(int m,int k){ int i,j; for(i=m;i>=k;i--){ a[k]=i; if(k>1) comb(i-1,k-1); else{ for(j=a[0];j>0;j--) cout<<a[j]<<" "; cout<<endl; } } } int main(){ int n,r; cin>>n>>r; if(r>n) cout<<"error"<<endl; else{ a[0]=r; comb(n,r); } }
非递归实现
时间复杂度为O(n^r),且r的大小已知,这样才能确定循环的层数。这种算法对于r比较小的时候可以考虑一下。#include<iostream> using namespace std; int main(){ int n=5,r=3,i,j,k,t; t=0; for (i=1;i<=n-r+1;i++) { for(j=j+1;i<n-r+2;j++) { for(k=j+1;k<=n-r+3;K++) { t=t+1; cout<<i<<":"<<j<<":"<<k<<endl; } } } cout<<"Total="<<t; }
相关文章推荐
- 递归实现hanoi塔问题算法
- 常用算法的递归实现问题分析(针对《数据结构与程序设计》by Robert.L.Kruse)
- 0-1背包问题经典算法(递归实现)
- 递归和分治思想4|八皇后问题 - 数据结构和算法34
- 【计算机算法分析】递归与分治策略——二分搜索与集合划分问题
- 算法分析——Hanoi塔问题(还是写不出来啊!)
- 机试算法讲解: 第43题 递归之汉诺塔问题
- 算法基础:递归---汉诺塔问题
- 【算法】 组合数问题非递归解法
- 算法学习之递归--N皇后问题
- 递归和分治思想4|八皇后问题 - 数据结构和算法34
- 全排列算法递归及STL实现,八皇后问题
- 全排列问题问题的两种算法--递归与字典序
- python算法和数据结构笔记--汉诺塔问题超详细递归过程图解(堆栈数据结构)
- 算法[递归]-棋盘覆盖问题
- 2705:扩号匹配问题(2.2基本算法之递归和自调用函数)
- 北大 算法 2.4 递归 汉诺塔问题手工解法以及编译过程
- 递归 汉诺塔问题 Java数据结构与算法
- 算法笔记——【递归】全排列问题
- 栈与递归的实现:n阶Hanoi塔的算法分析与源码