Problem C: magic pocket (knapsack problem)

Topic links : http://codeup.cn/problem.php?cid=100000583&pid=2

Description Title
has a magical pocket, the total volume was 40, with some variations of this article pockets, the total volume of these items must be 40. John now there are n items to be obtained, the volume of each item respectively a1, a2 ...... an. John may be selected from some of these items, if the total volume of the object 40 is selected, then use the magic pocket, John these items can be obtained. The question now is, John How many different ways of selecting items.

Input
of the first input line is a positive integer n (1 <= n <= 20), indicates the number of different items. The next n lines, each line has a positive integer between 1 and 40, respectively, give values a1, a2 ...... an a.

The output of
the number of different items selected output mode.

Sample input
2
12 is
28
. 3
21 is
10
. 5

Sample output
. 1
0

Code

#include<stdio.h>
#include<string.h> 
 
int pocket[30];

int slect(int a, int b) {    
	if(b == 0)   return 1;  //选择成功
	if(a <= 0)   return 0;  //选择失败
	return slect(a - 1, b)+slect(a - 1, b - pocket[a]);     
}
 
int main() {
	int n;
	while(scanf("%d", &n) != EOF) {
			for(int i = 1; i <= n; i++) {
				scanf("%d", &pocket[i]);
			}
			printf("%d\n", slect(n, 40));		
	}
	return 0;
}
Published 112 original articles · won praise 7 · views 10000 +

Guess you like

Origin blog.csdn.net/Rhao999/article/details/104100630