NO.1 递归实现指数型枚举
从 1∼n 这 n 个整数中随机选取任意多个,输出所有可能的选择方案。
输入格式
输入一个整数 n
输出格式
每行输出一种方案。
同一行内的数必须升序排列,相邻两个数用恰好 1
个空格隔开。
对于没有选任何数的方案,输出空行。
本题有自定义校验器(SPJ),各行(不同方案)之间的顺序任意。
数据范围
1≤n≤15
输入样例:
3
输出样例:
3 2 2 3 1 1 3 1 2 1 2 3
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
using namespace std;
const int N = 16;
int n;
int st[N];
//st 记录状态 0->没有考虑 1->选 2->不选
void dfs(int u){
if(u > n){
for(int i = 1;i <= n;i ++)
if(st[i] == 1)
printf("%d ",i);
printf("\n");
return;
}
st[u] = 2;
dfs(u + 1); //第一个分支:不选
st[u] = 0; //恢复现场
st[u] = 1;
dfs(u + 1); //第二个分支:选
st[u] = 0;
}
int main(){
cin >> n;
dfs(1);
return 0;
}
NO.2 递归实现排列型枚举
把 1∼n 这 n 个整数排成一行后随机打乱顺序,输出所有可能的次序。
输入格式
一个整数 n
输出格式
按照从小到大的顺序输出所有方案,每行 1
个。
首先,同一行相邻两个数用一个空格隔开。
其次,对于两个不同的行,对应下标的数一一比较,字典序较小的排在前面。
数据范围
1≤n≤9
输入样例:
3
输出样例:
1 2 3 1 3 2 2 1 3 2 3 1 3 1 2 3 2 1
方法一:暴搜(dfs)
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 10;
int n;
int st[N]; //0 -> 没有放数 1~n -> 放了哪个数
bool used[N]; //true -> 用过 false -> 未用过
void dfs(int u){
if(u > n){ // 边界
for(int i = 1;i <= n;i ++){ // 打印方案
cout << st[i];
}
cout << endl;
return;
}
// 依次枚举每个分支,即当前位置可以填哪些数
for(int i = 1;i <= n;i ++){
if(!used[i]){
st[u] = i;
used[i] = true;
dfs(u + 1);
//恢复现场
st[u] = 0;
used[i] = false;
}
}
}
int main(){
cin >> n;
dfs(1);
return 0;
}
//next-permutation
方法二:next-permutation函数 (头文件algorithm)
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
int n;
const int N = 16;
int a[N];
int main(){
cin >> n;
for(int i = 1;i <= n;i ++)
a[i] = i;
do{
for(int i = 1;i <= n;i ++){
cout << a[i] << " ";
}
cout << endl;
}
while(next_permutation(a+1 , a+1+n));
return 0;
}