[Daily question] Niu Ke: The minimum amount of currency to exchange money (one-dimensional dynamic programming)

Title description ( portal )

Given the array arr, all values ​​in arr are positive integers and do not repeat. Each value represents a currency of denomination, and any currency of each denomination can be used. Given an aim, which represents the amount of money to be found, find the minimum number of currencies that constitute the aim.
Enter description:

输入包括两行,第一行两个整数n(0<=n<=1000)代表数组长度和aim(0<=aim<=5000),第二行n个不重复的正整数,代表arr

Output description:

输出一个整数,表示组成aim的最小货币数,无解时输出-1.

Example

Example 1

输入
3 20
5 2 3
输出
4
说明
20=5*4

Example 2

输入
3 0
5 2 3
输出
0

Example 3

输入
2 2
3 5
输出
-1

Ideas

State definition:
dp[i]: represents the minimum number of sheets that compose i yuan

Initialization:
dp[0] = 0;
dp[i] = 1000;//i>0 takes the maximum value 1000.
State equation: The
for loop traverses the num array, and when the value of i is greater than num, the dp is updated, and it is responsible for not updating.
See the code explanation for details

dp[i] = Math.min(dp[i],dp[i - num[j]] + 1);

Return value:
dp[aim]

Code

import java.util.Arrays;
import java.util.Scanner;

/**
 * @ClassName Test1
 * @Description 换钱的最小货币数
 * @Author fff
 * @Date 2020/12/21/11:41
 */
public class Test1 {
    
    
    /*
    3 20
    5 2 3
    */
    private static int coinChange(int[] num, int amount) {
    
    
        //动态规划
        int[] dp = new int[amount + 1];
        dp[0]  = 0;

        for (int i = 1; i < dp.length; i++) {
    
    

            dp[i] = 1000;
            for (int j = 0; j < num.length; j++) {
    
    
                if (i >= num[j] && dp[i - num[j]] != 1000) {
    
    
                // 也可以不对1000做判断,那就得修改后边判断,将==改为 >=
                    dp[i] = Math.min(dp[i],dp[i - num[j]] + 1);// dp[i - num[j]] + 1其中1就是使用num[j]这张,在加dp[剩余钱数]
                }
            }
        }
        return dp[amount] == 1000 ? -1:dp[amount];
    }
    
    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        String[] str = scanner.nextLine().split(" ");
        int n = Integer.parseInt(str[0]);
        int amount = Integer.parseInt(str[1]);
        int[] num = new int[n];
        //String[] str1 = scanner.nextLine().split(" ");
        for (int i = 0; i < n; i++) {
    
    
            num[i] = scanner.nextInt();
        }
        System.out.println( coinChange(num , amount));
    }
}

Guess you like

Origin blog.csdn.net/weixin_45532227/article/details/111474909