换钱最少货币数-Java

换钱的最少货币数

http://www.nowcoder.com/questionTerminal/4e05294fc5aa4d4fa8eacef2e606e5a8

入门动态规划

import java.io.*;
import java.util.Arrays;
public class Main{
    public static void main(String[] args) throws IOException{
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String[] str = reader.readLine().split(" ");
        int[] arr = parse(str,2);
        int n = arr[0];
        int amount = arr[1];
        arr = parse(reader.readLine().split(" "),n);
        reader.close();
        System.out.println(coinChange(arr,amount));
    }
    private static int coinChange(int[] coins, int amount) {
        int max = amount + 1;
        int[] dp = new int[amount + 1];
        Arrays.fill(dp, max);
        dp[0] = 0;
        for (int i = 1; i <= amount; i++) {
            for (int j = 0; j < coins.length; j++) {
                if (coins[j] <= i) {
                    dp[i] = Math.min(dp[i], dp[i - coins[j]] + 1);
                }
            }
        }
        return dp[amount] > amount ? -1 : dp[amount];
    }

    private static int[] parse(String[] str,int len){
        int[] arr = new int[len];
        for(int i= 0;i < len;++i){
            arr[i] = Integer.parseInt(str[i]);
        }
        return arr;
    }
}
全部评论

相关推荐

评论
2
收藏
分享
牛客网
牛客企业服务