(Arithmetic exercises) - magic pocket

Requirements:
http://codeup.cn/problem.php?cid=100000583&pid=2
this question fully I feel I can write simple recursive (actually this is not difficult, but I think is not the case, then ... ... = = write to need to take a look some of the recursive code to achieve a look)
Code (Code refer to the god of writing, but also understand (but why can not think of it yourself?))

#include <stdio.h>
#include <string.h>
int count,n,sum;
int record[21];
void search(int index,int sum)
{
	if(sum==0)
	{
		count++;
		return;
	}
	if(index>=n)
		return;
	if(sum-record[index]>=0){
		search(index+1,sum-record[index]);
	}
	search(index+1,sum);	
}
int main(){
	int m;
	while(scanf("%d",&n) != EOF){
		for(int i = 0;i <n;i++){
			scanf("%d",&m);
			record[i] = m;
		}
		count = 0;
		search(0,40);
		printf("%d\n",count);
		memset(record,0,sizeof(record));
	}
}

Modified a bit to write a version of the cumulative sum (to have accumulated obsession = =)

#include <stdio.h>
#include <string.h>
int count,n,sum;
int record[21];
//利用index自动往后加1找到边界 
void search(int index,int sum)
{
	if(sum + record[index]==40)
	{
		count++;
	}
	if(index>=n){
		return;
	}
		
	if(sum + record[index]<40){
		search(index+1,sum + record[index]);
	}
	//这里的参数写的sum系统才给通过,但在本地测试,写search(index+1,0)也能得到答案,存疑
	search(index+1,sum);	
}
int main(){
	int m;
	while(scanf("%d",&n) != EOF){
		for(int i = 0;i <n;i++){
			scanf("%d",&m);
			record[i] = m;
		}
		count = 0;
		//相当于sum初始就是为0 
		search(0,0);
		printf("%d\n",count);
		memset(record,0,sizeof(record));
	}
}
Published 105 original articles · won praise 3 · Views 1964

Guess you like

Origin blog.csdn.net/weixin_42377217/article/details/103996647