Skip to content

Instantly share code, notes, and snippets.

@chenyanzhe
Created June 1, 2016 08:22
Show Gist options
  • Save chenyanzhe/58abf675a87904b7c2f594aa3ba1b320 to your computer and use it in GitHub Desktop.
Save chenyanzhe/58abf675a87904b7c2f594aa3ba1b320 to your computer and use it in GitHub Desktop.
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
if (amount <= 0) return 0;
// filter and fast path
vector<int> items;
for (auto c : coins) {
if (c < amount)
items.push_back(c);
else if (c == amount)
return 1;
}
// complete-packing problem
// bag capacity: amount
// capacity: coin value
// weight: 1
// target: minimal weight, fill the bag exactly
vector<int> dp(amount + 1, INT_MAX);
dp[0] = 0;
for (int i = 0; i < items.size(); i++) {
for (int v = items[i]; v <= amount; v++) {
dp[v] = min(dp[v], (dp[v - items[i]] == INT_MAX) ? INT_MAX : dp[v - items[i]] + 1);
}
}
return dp[amount] == INT_MAX ? -1 : dp[amount];
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment