递归实现组合型枚举
从 1∼n 这 n 个整数中随机选出 m 个,输出所有可能的选择方案。
输入格式
两个整数 n,m ,在同一行用空格隔开。
输出格式
按照从小到大的顺序输出所有方案,每行 1 个。
首先,同一行内的数升序排列,相邻两个数用一个空格隔开。
其次,对于两个不同的行,对应下标的数一一比较,字典序较小的排在前面(例如 1 3 5 7 排在 1 3 6 8 前面)。
数据范围
n>0 ,
0≤m≤n ,
n+(n−m)≤25
输入样例:
5 3
输出样例:
1 2 3
1 2 4
1 2 5
1 3 4
1 3 5
1 4 5
2 3 4
2 3 5
2 4 5
3 4 5
思考题:如果要求使用非递归方法,该怎么做呢?
算法实现:dfs,状态压缩,位运算
位运算,状态压缩
#include <iostream>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
vector<string> s;
int n, m;
int lowbit(int x)
{
return x & -x;
}
bool is_true(int x)
{
int res = 0;
while(x)
{
x -= lowbit(x);
res++;
}
if(res == m) return true;
return false;
}
int main()
{
cin >> n >> m;
for(int i = 0; i <= 1 << n; i++)
{
if(is_true(i))
{
string str = "";
for(int j = 0; j < n; j++)
{
if(i >> j & 1)
{
str += (char)(j + 1) + '0';
}
}
s.push_back(str);
}
}
sort(s.begin(), s.end());
for(auto str : s)
{
for(int i = 0; i < str.size(); i++) cout << str[i] - '0' << ' ';
puts("");
}
return 0;
}
dfs
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 30;
int n, m;
int a[N];
void dfs(int u, int v)
{
if(u == m + 1)
{
for(int i = 1; i <= m; i++) cout << a[i] << ' ';
puts("");
return;
}
for(int i = v; i <= n; i++)
{
a[u] = i;
dfs(u + 1, i + 1);
a[u] = 0;
}
}
int main()
{
cin >> n >> m;
dfs(1, 1);
return 0;
}