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

通过次数

0

提交次数

0

时间限制 : 1 秒 内存限制 : 128 MB


<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
……(太多,此处省略)

题目输入

题目输出

输入/输出样例

输入格式


                        

输出格式


                        

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;
}

Java解答

import java.util.Scanner;

public class Main {
	static int M,N;
	static int [] arr;
	public static void main(String[] args) {
		Scanner cin = new Scanner(System.in);
		M = cin.nextInt();
		N = cin.nextInt();
		arr = new int[N+1];
		combin(M,N);
	}
	public static void combin(int m,int n) {
		if(n == 0) {
			for(int i = 1; i <= N; i ++) {
				System.out.print(arr[i]);
				if(i == N)
					System.out.println();
				else
					System.out.print(" ");
			}
		}else if(m < n){
			return ;
		}else {
			combin(m-1,n);
			arr[n] = m;
			combin(m-1,n-1);
			}
		}
}