遞歸實現組合型枚舉

從 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 

AC代碼

#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
int way[50];
int n, m;
void dfs(int cnt, int start)
{
	if (cnt > m)
	{
		for (int i = 1; i <= m; i++)
		{
			printf("%d ", way[i]);
		}
		printf("\n"); 
		return;
	}
	for (int i = start; i <= n; i++)
	{
		way[cnt] = i;
		dfs(cnt + 1, i + 1);
	}
}
int main()
{
	cin >> n >> m;
	dfs(1, 1);
	return 0;
}
#include <iostream>
#include <cstdio>
using namespace std;
int n, m;
int ans[50];
void dfs(int step, int cnt)
{
	if (cnt == m)
	{
		for (int i = 1; i <= m; i++)
		{
			printf("%d ", ans[i]);
		}
		printf("\n");
		return ;
	}
	if (step == n)
	{
		return;
	}
	cnt++;
	ans[cnt] = step + 1;
	dfs(step + 1, cnt);
	ans[cnt] = 0;
	cnt--;
	dfs(step + 1, cnt);
}
int main()
{
	cin >> n >> m;
	dfs(0, 0);
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章