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)。
阅读全文
0 0
- Coin Change
- Coin Change
- Coin change
- Coin Change
- Coin change
- Coin Change
- Coin Change
- Coin Change
- Coin Change
- Coin Change
- Coin Change
- Coin Change
- Coin Change
- Coin Change
- Coin Change
- Coin Change
- coin change
- Coin Change
- Visual C++异常处理机制原理与应用(三)——C/C++结构化异常处理之try-except异常处理的使用(上)
- JDBC—JDBC中的异常处理
- Bzoj5088 HDU 6000 Wash
- 相似性度量—距离2
- 为什么要学习硬件
- Coin Change
- Codeforces Round #449 div2 C(递归求解)
- Codeforces Round #422 (Div. 2) C Hacker, pack your bags! (二分orDP)
- Object.prototype.toString.call(obj)检测对象类型?
- 日记:opencv3.0以后的版本变化
- 欢迎使用CSDN-markdown编辑器
- NVIDIA TK1 学习笔记(2):环境配置
- shadowsockets搭建
- poj1001在测试他给的数据结果一模一样,但总是wrong answer