算法竞赛进阶指南打卡系列题解
题目
原题链接
题面
从 1 ∼ n 1∼n 1∼n 这 n n n 个整数中随机选取任意多个,输出所有可能的选择方案。
输入格式
输入一个整数
n
n
n。
输出格式
每行输出一种方案。
同一行内的数必须升序排列,相邻两个数用恰好 1 1 1 个空格隔开。
对于没有选任何数的方案,输出空行。
本题有自定义校验器(SPJ),各行(不同方案)之间的顺序任意。
数据范围
1
≤
n
≤
15
1≤n≤15
1≤n≤15
输入样例:
3
输出样例:
3
2
2 3
1
1 3
1 2
1 2 3
注:第一行行也是一组解,输出空
题解
思路1
简简单单暴搜一下即可。
代码1
#include <bits/stdc++.h>
// #define int long long
using namespace std;
typedef long long LL;
const int N = 20;
int n;
int path[N];
bool st[N];
void dfs(int u)
{
if (u == n) {
for (int i = 0; i < n; i ++ ) {
cout << path[i] << " ";
}
cout << "\n";
return;
} else {
for (int i = 0; i < u; i ++ ) {
cout << path[i] << " ";
}
cout << "\n";
}
for (int i = u == 0 ? 1 : path[u - 1] + 1; i <= n; i ++ ) {
if (st[i]) continue;
path[u] = i;
st[i] = true;
dfs(u + 1);
st[i] = false;
}
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin >> n;
dfs(0);
return 0;
}
思路2
回想前几道题的位运算,由于 n n n 最大为15,我们可以采用状态压缩的方式,其中二进制数为 0 0 0 的位置表示不选, 1 1 1表示选。
代码2
y总的递归写法(递归竟然比直接写还长,可以但没有必要doge)
下方是直接写的代码:
#include <bits/stdc++.h>
// #define int long long
using namespace std;
typedef long long LL;
signed main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
for (int i = 0; i < 1 << n; i ++ ) {
for (int j = 0; j < n; j ++ ) {
if (i >> j & 1) {
cout << j + 1 << " "; // 二进制位为0 ~ n-1,因此需要加1
}
}
cout << "\n";
}
return 0;
}