两个古老问题的递归算法。
来源:互联网 发布:微pe 知乎 编辑:程序博客网 时间:2024/05/17 20:39
1. 全排列
思路1:递归分治(基于交换)
#include <stdio.h>void perm(int* a, int start, int end);void swap(int& m, int& n);void output(const int* a, int size);int main() {int a[5] = {1, 2, 3, 4, 5};perm(a, 0, 5);return 0;}void perm(int* a, int start, int end) {if(start == end - 1) {output(a, end);} else {for(int i = start; i < end; ++i) {swap(a[start], a[i]);perm(a, start + 1, end);swap(a[start], a[i]);}}}void swap(int& m, int& n) {int t = m;m = n;n = t;}void output(const int* a, int size) {static int count;printf("%3d: ", ++count);for(int i = 0; i < size; ++i) {printf("%d ", a[i]);}printf("\n");}
思路2:剪枝回溯
#include <stdio.h> void perm(int* data, int* buf, int start, int end);void output(const int* a, int size);int main() {int data[5] = {1, 2, 3, 4, 5};int buf[5] = {0};perm(data, buf, 0, 5);return 0;}void perm(int* data, int* buf, int start, int end) {if(start == end) {output(buf, end);} else {for(int i = 0; i < end; i++) {if(!data[i]) continue;buf[start] = data[i];data[i] = 0;perm(data, buf, start + 1, end);data[i] = buf[start];}}}void output(const int* a, int size) {static int count;printf("%3d: ", ++count);for(int i = 0; i < size; ++i) {printf("%d ", a[i]);}printf("\n");}
2. 汉诺塔
#include <stdio.h>void hanoi(int n, char a, char b, char c);void move(int n, char from, char to);int main() {hanoi(5, 'A', 'B', 'C');return 0;}void hanoi(int n, char a, char b, char c) {if(n > 0) {hanoi(n - 1, a, c, b);move(n, a, b);hanoi(n - 1, c, b, a);}}void move(int n, char from, char to) {static int step;printf("Step %3d: No.%d %c -> %c.\n", ++step, n, from, to);}
- 两个古老问题的递归算法。
- 古老的火车问题
- 快速排序,古老的算法
- 算法---求两个数的最大公约数(递归)
- 算法竞赛入门经典--古老的密码
- ctfIDF实验室古老的邮件编码问题
- 古老的CSS同高列问题
- 汉诺塔问题的递归算法
- 背包问题的递归算法
- java-两个递归问题
- 计算两个文件的相对路径的递归算法
- 字节对齐问题----一个很古老的基础问题
- 关于中国古老的一个问题,百钱百鸡问题
- 判别两个广义表是否相等的递归算法
- 合并两个排序的链表(递归算法)
- 判别两个广义表是否相等的递归算法。
- 递归算法与两个经典问题:汉诺塔问题和八皇后问题
- 一道古老的智力题——奇怪的问题
- 天龙 - Action Buffer
- vc++ resource.h文件出现“fatal error RC1004: unexpected end of file found”问题 .
- android中 sqlite数据库插入速度的优化
- Eclipse快捷键指南
- VC用ADO连接oracle的方法 .
- 两个古老问题的递归算法。
- Ogre - Memory , Introduction
- 我php函数 2 字符串
- Jxls导出excel的若干方式总结(八)-- 导出一条查询记录到多个sheet
- Windows批处理命令
- OGRE - MultiThread
- Android中的内存管理
- VisionMobile: 开放管控指数(四) -- 开源管控:Eclipse
- android string.xml中的string转义