Coin Change

来源:互联网 发布:pdf.js ajax 编辑:程序博客网 时间:2024/06/10 01:49

原题链接: https://leetcode.com/problems/coin-change/description/

题目: 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.

Solution: 采用动态规划的思想,用needCoins[i]表示用给定面额的硬币coins组成指定数额amount的最小硬币数量,如果该数额不能由给定的硬币组成,则needCoins[i]就置为INT_MAX,如果我们能计算出所有的needCoins[i]值,那么needCoins[amount]就是答案。

状态转移方程为:
needCoins[i] = min(needCoins[i-coins[1]], needCoins[i-coins[2]], ….., needCoins[i-coins[k]], ) + 1;

class Solution {public:    int coinChange(vector<int>& coins, int amount) {        int needCoins[amount+1];        needCoins[0] = 0;        for (int i = 1; i <= amount; ++i) {            int need = INT_MAX;            for (int j = 0; j < coins.size(); j++) {                if (i - coins[j] >= 0 && needCoins[i - coins[j]] != INT_MAX) {                    need = min(need, needCoins[i - coins[j]] + 1);                }            }            needCoins[i] = need;        }        return needCoins[amount] == INT_MAX ? -1 : needCoins[amount];    }};

复杂度: 给定的数额amount为S, 硬币的面额有K种,那么,上述算法的复杂度为O(S*K)。

原创粉丝点击