zoukankan      html  css  js  c++  java
  • 0322. Coin Change (M)

    Coin Change (M)

    题目

    You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.

    Example 1:

    Input: coins = [1, 2, 5], amount = 11
    Output: 3 
    Explanation: 11 = 5 + 5 + 1
    

    Example 2:

    Input: coins = [2], amount = 3
    Output: -1
    

    Note:
    You may assume that you have an infinite number of each kind of coin.


    题意

    选数量最少的硬币,使其和为amount。

    思路

    动态规划,由局部最优解求得全局最优解:设F(N)为和为N的硬币的最小个数,C为某一硬币的面值,那么很容易得到 F(N) = F(N - C) + 1,那么只要求得F(N - C)的最小值,就能得到F(N)的最小值。


    代码实现

    Java

    记忆化

    class Solution {
        public int coinChange(int[] coins, int amount) {
            return dfs(coins, amount, new int[amount + 1]);
        }
    
        private int dfs(int[] coins, int remain, int[] record) {
            if (remain < 0) {
                return -1;
            }
            if (remain == 0) {
                return 0;
            }
            if (record[remain] != 0) {
                return record[remain];
            }
    
            int min = Integer.MAX_VALUE;
            for (int coin : coins) {
                int count = dfs(coins, remain - coin, record);
                if (count >= 0 && count + 1 < min) {
                    min = count + 1;
                }
            }
    
            record[remain] = min == Integer.MAX_VALUE ? -1 : min;
            return record[remain];
        }
    }
    

    动态规划

    class Solution {
        public int coinChange(int[] coins, int amount) {
            int[] dp = new int[amount + 1];
            Arrays.fill(dp, amount + 1);
            dp[0] = 0;
            for (int i = 1; i <= amount; i++) {
                for (int coin : coins) {
                    if (i >= coin) {
                        dp[i] = Math.min(dp[i], dp[i - coin] + 1);
                    }
                }
            }
            return dp[amount] == amount + 1 ? -1 : dp[amount];
        }
    }
    
  • 相关阅读:
    权限设计=功能权限+数据权限
    C# 自定义配置文件
    asp.net core 系列 2 启动类 Startup.CS
    asp.net core 系列 1 概述
    IOC : Unity 配置和使用
    Unity Ioc 依赖倒置及Untity AOP被动拦截/自动拦截
    webuploader-异步切片上传(暂不支持断点续传)及 下载方法!C#/.NET
    C# 构造基础返回值类型-BaseResponse
    神奇的选择器 :focus-within
    妙用 scale 与 transfrom-origin,精准控制动画方向
  • 原文地址:https://www.cnblogs.com/mapoos/p/13197372.html
Copyright © 2011-2022 走看看