Dynamic Planning magical pocket

Links: https://www.nowcoder.com/questionTerminal/9aaea0b82623466a8b29a9f1a00b5d35?orderByHotValue=0&commentTags=C/C++
Source: Cattle-off network

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.

 

Enter a description:
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.


Output Description:
The number of different items of output selection mode.
Example 1

Entry

3
20
20
20

Export

3 


and a typical 01 knapsack problem
import java.util.*;
public class Main {
    public static void main(String[] args) {
        System.out.println(much());
    }

    public static int much() {

        Scanner scanner = new Scanner(System.in);
        int big = 40;
            int n = scanner.nextInt();
            int[] array = new int[n + 1];
            int[][] dp = new int[n + 1][big + 1];

            for (int i = 0; i <= n; i++) {
                dp[i][0] = 1;
            }

            for (int j = 1; j <= big; j++) {
                dp[0][j] = 0;
            }
            for (int i = 1; i <= n; i++) {
                array[i] = scanner.nextInt();
            }


            for (int i = 1; i <= n; i++) {
                for (int j = 1; j <= big; j++) {
                    if (j >= array[i]) {
                        dp[i][j] = dp[i - 1][j] + dp[i - 1][j - array[i]];
                    } else {
                        dp[i][j] = dp[i - 1][j];
                    }
                }

            }
            return dp[n][big];
        }


}

 

Guess you like

Origin www.cnblogs.com/hetaoyuan/p/11334955.html