codeup magic pocket (C ++)

Title Description

There is a magic 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.

Entry

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.

Export

The number of different items of output selection mode.

Sample input  Copy

2
12
28
3
21
10
5

Sample output Copy

1
0

Outline of Solution: It is a 0-1 knapsack problem, something in the backpack into n m of capacity, each into a thing m = m - a [n], n = n - 1. Recursive boundary: when the backpack capacity exactly 0, 1 return; capacity is smaller than 0 when the backpack (i.e. can not be put into something), or after all items to put the backpack capacity is still not equal to 0 (i.e., when n == 0) , 0 is returned at this time.

#include <stdio.h>
#include <iostream>
using namespace std;
int a[20]={0};
int F(int m,int n)     // 容量为 m 的背包里放进前 n 个物品
{
    if(m==0)          // 背包正好装满,此时容量为0,是合适的方案,返回 1 
        return 1;
    if(n==0 || m<0)  // 当背包里只能放进去0个物品或者背包的容量小于0,此时返回 0
        return 0;
    return F(m,n-1)+F(m-a[n],n-1);
 
}
 
int main()
{
    int n;
    while(scanf("%d",&n)!=EOF)
    {
        for(int i=1;i<=n;i++)
            scanf("%d",&a[i]);
        printf("%d\n",F(40,n));
    }
    return 0;
}

 Reference blog: https://blog.csdn.net/Zizizi9898/article/details/89212550

https://blog.csdn.net/LoveHYZH/article/details/88026078

 

Published 32 original articles · won praise 2 · Views 1614

Guess you like

Origin blog.csdn.net/qq_38969094/article/details/104349992