Leetcode之CoinChange

题目

题目地址 https://leetcode.com/problems/coin-change/
 

  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:
coins = [1, 2, 5], amount = 11
return 3 (11 = 5 + 5 + 1)

Example 2:
coins = [2], amount = 3
return -1.

解题

  典型的动态规划问题,满足最优子结构和重复子问题。
  定义问题的最优解:即当零钱为amount时最少需要哪些硬币。
  最优解的值为:零钱为amount时候的最少硬币数。
  递归式求解:令f[i]为当amount为i时最少需要的硬币数,则对于某一个coin[j]满足,i>=coin[j] 则剩余的零钱数为i-coin[j],硬币数+1。递归式可写成如下:
  

f[i] = Math.min(f[i],f[i-coin[j]]+1);

定义初始值:f[0]=0。

Code



/**
 * Created by bamboo on 2016/10/17.
 */
public class CoinChange {
    /**
     * 找出零钱为amount时候最少需要的硬币数
     * @param coins
     * @param amount
     * @return
     */
    public int coinChange(int[] coins, int amount) {
        int[] f = new int[amount + 1];
        f[0] = 0;
        for (int i = 1; i <= amount; i++) {
            f[i] = Integer.MAX_VALUE;
            for (int j = 0; j < coins.length; j++) {
                /*满足计算条件*/
                if (i >= coins[j] && f[i - coins[j]] != Integer.MAX_VALUE) {
                    f[i] = Math.min(f[i], f[i - coins[j]] + 1);
                }
            }
        }
        return f[amount] == Integer.MAX_VALUE ? -1 : f[amount];
    }


}

令人意外超过居然达到了80%,特此纪念
这里写图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值