这道就是DFS的入门题。没啥好说的
唯一要注意的可能就是输出格式吧,记得有空行
#include<cstdio> #include <cstring> using namespace std; int n,cnt = 0; int vis[21],A[21]; //一般使用全局变量 //dfs通过全局变量来控制子函数 //素数表,加快后续判断 int prime[38] = {0,0,1,1,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,0,0,0,0,1,0,1,0,0,0,0,0,1}; void dfs(int step) { int r = 0; if(step == n && prime[A[0]+A[n-1]]) { printf("%d", A[0]); for(int i = 1; i < n; ++i) printf(" %d", A[i]); printf("\n"); } else { for(int i = 2; i <= n; i++) { if(vis[i] == 0 && prime[A[step-1] + i]) { vis[i] = 1; A[step] = i; dfs(step+1);//dfs的精髓! vis[i] = 0;//不要忘记重置这个数字的状态,因为需要再次使用 } } } } int main() { while(~scanf("%d", &n)) { memset(vis, 0, sizeof(vis)); A[0] = 1; //这个初始化很重要,不然A[0]就等于0了,结果会错的 printf("Case %d:\n", ++cnt); dfs(1); printf("\n"); } }