leetcode笔记: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.

Note:

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

二. 题目分析

题目大意是,给定不同面值的硬币(数值存放在数组coins)和一个金额总值amount。编写函数计算凑齐金额总值所最少需要的硬币数目。如果使用已有的硬币无法凑齐指定的金额,返回-1

对于本题目,若使用贪心算法是不可行的,因为有可能会错过全局最优解。

该问题可使用动态规划来解决,构建一个数组dp[amount + 1]用于记录从0 ~ amount每个数用coins组合的最小次数(对于每个数,组合次数的上限不可能超过amount + 1,因此可将数组初始化为amount + 1,这样,对于某一下标i,只要出现合法的组合,就可以使用min函数覆盖掉amount + 1,若执行算法后该下标所对应的值仍为amount + 1,说明无法在coins中找出一个组合来表示i)

根据以上思路,可写出状态转移方程:

dp[x + coins] = min(dp[x] + 1, dp[x + coins])

其中dp[x]代表凑齐金额x所需的最少硬币数,coins表示可用的硬币面值,在coins数组中遍历。

注意在算法执行前,令dp[0] = 0。

discuss中给出了更高效的深搜方法,相对来说代码比较复杂,如下方第二段代码所示。

三. 示例代码

// DP,时间复杂度:O(n*amount)
class Solution {
public:
    int coinChange(vector<int>& coins, int amount) {
        if (amount < 0) return -1;
        if (amount == 0) return 0;
        // 硬币组合个数不可能大于amount,因此若某下标的元素值
        // 为amount + 1说明无法用coins里的硬币组合出该下标
        vector<int> dp(amount + 1, amount + 1);
        dp[0] = 0;
        for (int i = 1; i < amount + 1; ++i)
            for (int j = 0; j < coins.size(); ++j)
                if (coins[j] <= i)
                    dp[i] = min(dp[i], dp[i - coins[j]] + 1);

        return dp[amount] > amount ? -1 : dp[amount];
    }
};
// DFS
class Solution {
public:
    int currBestResult;

    void solve(const vector<int>::iterator & begin, const vector<int>::iterator & end, int amount, int currCount)
    {
        // find a solution, update currBestResult if this is better
        if(amount == 0) {
            if(currBestResult == -1)
                currBestResult = currCount;
            else
                currBestResult = min(currBestResult, currCount);
            return;
        }

        // use up all coin types, no solution
        if(begin == end) return;
        // can‘t achiveve a solution better than currBestResult, no need to explore more
        if(currBestResult != -1 && currBestResult <= amount / *begin + currCount) return;

        int count, currAmount;
        // start from the largest remaining coin first
        for (auto it = begin; it != end; ++it) {
            int coin = *it;
            // use coin as much as possible, so that we can get a good solution early to save exploration
            currAmount = amount % coin;
            count = amount / coin;
            while(currAmount < amount) {
                // find solutions to fill currAmount with smaller coins
                solve(it + 1, end, currAmount, count + currCount);
                // scale back by one largest coin to extend currAmount to try solve again in the next iteration
                currAmount += coin;
                count--;
            }
        }
    }

    int coinChange(vector<int>& coins, int amount) {
        currBestResult = -1;
        sort (coins.begin(), coins.end(), greater<int>());
        solve(coins.begin(), coins.end(), amount, 0);
        return currBestResult;
    }
};

四. 小结

动态规划的经典题目,值得学习。

时间: 2024-10-13 09:28:21

leetcode笔记:Coin Change的相关文章

[LeetCode][JavaScript]Coin Change

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 o

leetcode 518. Coin Change 2/硬币找零 2

归纳于http://www.cnblogs.com/grandyang/p/7669088.html 原题https://leetcode.com/problems/coin-change-2/description/ 518. Coin Change 2(Medium) You are given coins of different denominations and a total amount of money. Write a function to compute the numbe

【Leetcode】Coin Change

题目链接: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 mone

LeetCode 518. Coin Change 2

一看就是用dp来做,但是这道题还是有点意思的. dp[i] = sum_{coin} dp[i-coin] 上述的递推公式看似很对,但是会把重复的情况都考虑进去.举个例子,算dp[5]的时候,dp[5]=dp[0]+dp[4]+dp[3],但是之前算的dp[4]就是从dp[3]计算得到的. 解决办法是,一个一个硬币更新dp,即 dp[i] += dp[i-coin] for each coin.这样,对于当前的coin,dp[i-coin] 一定是不会包含当前coin的. class Solut

(Java) LeetCode 322. 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,

LeetCode OJ 322. Coin Change DP求解

题目链接:https://leetcode.com/problems/coin-change/ 322. Coin Change My Submissions Question Total Accepted: 15289 Total Submissions: 62250 Difficulty: Medium You are given coins of different denominations and a total amount of money amount. Write a func

Leetcode OJ --- 322. 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,

leetcode笔记

leetcode 笔记 Linked List 2. Add Two Numbers You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a

dp背包问题/01背包,完全背包,多重背包,/coin change算法求花硬币的种类数

一步一步循序渐进. Coin Change 具体思想:给你 N元,然后你有几种零钱S={S1,S2...,Sm} (每种零钱数量不限). 问:凑成N有多少种组合方式  即N=x1 * S1+x2*S2+...+xk*Sk (xk>=0,k=1,2..m) 设有f(x)中组合方式 有两种解答(自底向上回溯): 1.不用第m种货币   f(N,m-1) 2.用第m种货币 f(N-Sm,m) 总的组合方式为f(N,m)=f(N,m-1)+f(N-Sm,m) anything is nonsense,s

HDU 2069 Coin Change

Coin Change Time Limit: 1000ms Memory Limit: 32768KB This problem will be judged on HDU. Original ID: 206964-bit integer IO format: %I64d      Java class name: Main Suppose there are 5 types of coins: 50-cent, 25-cent, 10-cent, 5-cent, and 1-cent. We