如上图。在遍历一个图时采用搜到底再回头的想法,遍历顺序为
A
−
>
B
−
>
D
−
>
E
−
>
G
−
>
C
−
>
F
A->B->D->E->G->C->F
A−>B−>D−>E−>G−>C−>F。时间复杂度为
O
(
2
n
)
O(2^n)
O(2n)。
在竞赛中,一般程序运行时间为 1 s 1s 1s 或 2 s 2s 2s,那么我们按 2 s 2s 2s 来计算,计算机每秒可以运算约 1 0 9 10^9 109 次,那么在规定时间内就可以运算 log 2 2 × 1 0 9 ≈ 30 \log_2{2 \times 10^9} \thickapprox 30 log22×109≈30 次。也就是说,当对象大于等于 30 30 30 个时,程序会超时。
当题目中的对象太大时,就不能直接暴力搜索了,需要在搜索的过程中进行取舍,也就是 剪枝。
剪枝有以下几个方法:
1.记忆化搜索
其实记忆化搜索就是所谓的 DFS
,就是将已经搜索过的、不需要再搜索的打上标记,下一次搜索的时候直接跳过这种情况,可以大大优化程序效率。
例:全排列问题
给你 n n n 个数,生成这 n n n 个数的全排列。
样例:
输入:
3
1 2 3
输出:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
标程:
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <float.h>
#include <ctype.h>
#include <map>
#include <stdbool.h>
using namespace std;
int n;
int a[1005], b[1005];
void dfs(int t) {
if(t == n+1) {
for(int i = 1; i <= n; i++)
printf("%5d", a[i]);
printf("\n");
return ;
}
for(int i = 1; i <= n; i++) {
if(b[i]) continue;
a[t] = i, b[i] = 1; // 这就是记忆化(也叫搜索与回溯)
dfs(t+1);
a[t] = 0,b[i] = 0;
}
}
int main() {
scanf("%d", &n);
dfs(1);
return 0;
}