Niuniu's knapsack problem

【question】

Niuniu is going to participate in the spring outing organized by the school. Before departure, Niuniu is going to put some snacks into his backpack. Niuniu's backpack has a capacity of w.

There are a total of n bags of snacks in Niuniu’s family, and the volume of the i-th bag is v[i].

Niuniu wants to know how many ways to put snacks in total if the total volume does not exceed the capacity of the backpack (a total volume of 0 is also counted as one way to put it).

Enter description:

Input consists of two lines
The first line is two positive integers n and w (1 <= n <= 30, 1 <= w <= 2 * 10^9), which represent the number of snacks and the capacity of the backpack.
The second line contains n positive integers v[i] (0 <= v[i] <= 10^9), which represent the volume of each bag of snacks.

Output description:

Output a positive integer, indicating how many kinds of snacks there are in Niu Niu.

Example 1

enter

3 10
1 2 4

output

8

illustrate

The total volume of the three kinds of snacks is less than 10, so each snack can be put in or not put in, a total of 2*2*2 = 8 cases.

【solve】

① For each snack, there are two cases, not add it to the backpack or add it to the backpack. dfs implementation.

import java.util. *;

public class Main{
    static int count = 0;
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int w = sc.nextInt();
        int[] v = new int[n];
        long sum = 0;
        count = 0;
        for (int i = 0;i < n;i ++){
            v[i] = sc.nextInt();
            sum += v[i];
        }
        if (sum <= w){
            System.out.println((int)Math.pow(2,n));
        }else {
            dfs(0,0,n,v,w);
            System.out.println(count + 1);
        }
    }
    public static void dfs(long cursum,int index,int n,int[] v,int w){
        if (index < n){
            if (cursum > w){
                return;
            }
            dfs(cursum,index + 1,n,v,w);
            if (cursum + v[index] <= w){
                count ++;
                dfs(cursum + v[index],index + 1,n,v,w);
            }
        }
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325064605&siteId=291194637