[leetcode]Coin Change
链接:https://leetcode.com/problems/coin-change/description/
Question
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
You may assume that you have an infinite number of each kind of coin.
Solution
class Solution {
public:
#define inf 0x3fffffff
vector<int> coins;
map<int, int> mp;
int dfs(int target) {
if (mp.find(target) != mp.end()) return mp[target];
if (target == 0) return 0;
else if (target < 0) return inf;
int res = inf;
for (int i = 0; i < coins.size(); i++) {
int temp = dfs(target-coins[i]);
if (temp != -1) res = min(res, 1+temp);
}
mp[target] = res;
return res;
}
int coinChange(vector<int>& coins, int amount) {
this->coins = coins;
int ans = dfs(amount);
if (ans == inf) ans = -1;
return ans;
}
};
思路:采用递归和状态压缩的方法,对于每一次,遍历所有的coin看是不是可以满足。dfs的含义是当前target可以由多少个coin所组成。