2020 Guangxi University final C language question bank-output combination question solution

2020 Guangxi University final C language question bank-output combination problem solution

This is the problem portal

Topic refinement: Choose r numbers from 1, 2, 3...n (in no particular order ) to form a combination.
Output requirement: use recursive method to output all combinations from small to large

Key point explanation:
No order: r numbers of each combination cannot be repeated. ps->123/321 is repeated.

So, all the cases where C r(up) n(down) – this is a mathematical symbol – are output

#include<stdio.h>
long long n, r,arr[50000];/*arr数组作为空间容器:比如123,用arr[1]=1,
arr[2]=2,arr[3]=3来承装。*/

Recursive function body:

void func ( long long step,long long t ) {
    
    //step是表示第几个数,step=1表示r个数字的第一个数字
	if ( step == r+1 )//边界条件:已选出r个数,输出
	{
    
    
		for ( int j = 1; j <= r; j++ )
			printf ( "%lld", arr[j] );
		printf ( "\n" );
		return;//返回最近的一次调用函数
	}
	for ( long long i = t+1; i <= n-r+step; i++ )//i从t+1开始,就是从比上一位大的数字里选择:1__,第二位要选择比1大的,防止重复
	{
    
    
			arr[step] = i;//给第step位数赋值
			func ( step + 1, i );//递归,对下一位操作
	}
	return;//返回最近的一次调用函数
}

Main function:

int main ()
{
    
    
	long long k;
	scanf ( "%lld", & k );//k组数据
	while ( k-- )
	{
    
    
		scanf ( "%lld %lld", &n, &r );
		func ( 1, 0 );//选对第一个数的位置操作,因为从1~n,所以t=0.
	}
	return 0;
}

Rough process picture:
Insert picture description here
Total code:

#include<stdio.h>
long long n, r,arr[50000];

void func ( long long step,long long t ) {
    
    
	if ( step == r+1 )
	{
    
    
		for ( int j = 1; j <= r; j++ )
			printf ( "%lld", arr[j] );
		printf ( "\n" );
		return;
	}
	for ( long long i = t+1; i <= n-r+step; i++ )
	{
    
    
			arr[step] = i;
			func ( step + 1, i );
	}
	return;
}
int main ()
{
    
    
	long long k;
	scanf ( "%lld", & k );
	while ( k-- )
	{
    
    
		scanf ( "%lld %lld", &n, &r );
		func ( 1, 0 );
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_51550966/article/details/112338773
Recommended