谁告诉你题目上写递归比必须用递归了
递归实现指数枚举:
#include <bits/stdc++.h>
using namespace std;
signed main()
{
int n;
cin >> n;
for (int mask = 0; mask < (1 << n); mask ++, cout << '\n')
for (int i = 0; i < n; i ++)
if (mask & (1 << i))
cout << i + 1 << ' ';
return 0;
}
递归实现组合枚举:
#include <bits/stdc++.h>
using namespace std;
signed main()
{
int n, m;
cin >> n >> m;
for (int mask = (1 << n) - 1; ~mask; mask --) if (__builtin_popcount(mask) == m)
{
for (int i = n - 1; ~i; i --)
if (mask & (1 << i))
cout << n - i << ' ';
cout << '\n';
}
return 0;
}
递归实现排列型枚举
#include <bits/stdc++.h>
using namespace std;
signed main()
{
int a[10];
int n;
cin >> n;
for (int i = 1; i <= n; i ++)
a[i] = i;
do for (int i = 1; i <= n; i ++)
cout << a[i] << ' ';
while (cout << '\n', next_permutation(a + 1, a + n + 1));
return 0;
}