标签:
1AC. Intuitive DP. But please note the if condition, there‘s a trick - we cannot build upon an invalid dp slot.
class Solution { public: int coinChange(vector<int>& coins, int amount) { int n = coins.size(); if (!n) return -1; vector<int> dp(amount + 1, INT_MAX); dp[0] = 0; for (int i = 1; i <= amount; i ++) for (auto c: coins) { int prev = i - c; if (i >= c && (prev?dp[prev]!=INT_MAX : true)) { dp[i] = min(dp[i], dp[prev] + 1); } } return (dp[amount] == INT_MAX) ? -1 : dp[amount]; } };
标签:
原文地址:http://www.cnblogs.com/tonix/p/5106607.html