Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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];
    }
};

 

posted on 2016-01-06 18:29  Tonix  阅读(188)  评论(0编辑  收藏  举报