Dynamic programming to solve the problem: the number and the number of methods for sum

Title description: The
number of sums is the number of methods of sum (given an array A with n positive integers and an integer sum, find the number of options in which the sum of some numbers in the array A is sum. When the two options have one number If the subscript is not the same, we think it is a different composition scheme.)

Input description: The
input is two lines: the
first line is two positive integers n (1 ≤ n ≤ 1000), and the
second line is n positive integers Ai , separated by spaces.

Example 1
Input
5 15 5 5 10 2 3
Output
4

This problem is actually a bit awkward. In order to better solve this problem, the preferred method is of course dynamic programming:
the core idea of ​​dynamic programming is to decompose the big problem into sub-problems, solve the sub-problems, and then The answers to the sub-questions are combined to get the answer to the final question.

If we do not use dynamic programming, we will use the original method, similar to permutation and combination, and its complexity is very high.

Here focuses on the solution of dynamic programming.
Insert picture description here

The above is the table obtained using dynamic programming, and finally the last value of the array is successful.

package pracetice;

import java.util.Scanner;

public class Dp {
    
    
    public static void main(String[] args) {
    
    
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();
        int sum=sc.nextInt();
        int[] num=new int[n];
        for(int i=0;i<n;i++){
    
    
            num[i]=sc.nextInt();
        }
        System.out.println(getCount(num, sum));
    }

    private static long getCount(int[] num, int sum) {
    
    
        long[][] arr=new long[num.length+1][sum+1];
        for(int i=0;i<=num.length;i++){
    
    
            arr[i][0]=1;
        }
        for(int j=1;j<=sum;j++){
    
    
            arr[0][j]=0;
        }
        for(int i=1;i<arr.length;i++){
    
    
            for(int j=1;j<arr[0].length;j++){
    
    
                if(num[i-1]<=j){
    
    
                    arr[i][j]=arr[i-1][j]+arr[i-1][j-num[i-1]];
                }
                else{
    
    
                    arr[i][j]=arr[i-1][j];
                }
            }
        }
        return arr[num.length][sum];
    }
}

Guess you like

Origin blog.csdn.net/weixin_43815275/article/details/113555185