游客 Signup | Login
中文 | En

2140 - 【搜索基础】组合的输出


<span style="font-size:18px;"><strong>组合的输出</strong></span> 

<strong>compages.pas/c/cpp</strong> 

<br />

<span style="font-size:18px;">[问题描述]</span> 

从n个数中取出r个元素,输出所有组合
[输入格式]
一行两个自然数n和r (1<n<21,1<=r<=n)
[输出格式]
所有的组合,每个组合占一行,其中的元素从小到大排序,用一个空格隔开,所有组合按字典序。
[输入样例]
5 3
[输出样例]
1 2 3
1 2 4
1 2 5
1 3 4
……(太多,此处省略)

Input

Output

Examples

Input


                

Output


                

Solution C++

#include<cstdio>
#include<cstdlib>
#include<iostream>
using namespace std;
int n,r;
bool a[25]={0};
int b[25];
int print()
{
	for(int i=1;i<=r-1;++i)
	{
		printf("%d ",b[i]);
	}
	printf("%d\n",b[r]);
}
int search(int i)
{
	for(int j=1;j<=n;++j)
	{
		if(a[j]==0&&j>b[i-1])
		{
			b[i]=j;
			a[j]=1;
			if(i==r)
			{
				print();
			}
			else
			{
				search(i+1);
			}
			a[j]=0;
		}
		
	}
}
int main()
{
	cin>>n>>r;
	search(1);
	return 0;
}
Time Limit 1 second
Memory Limit 128 MB
Discuss Stats
上一题 下一题