码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode "Coin Change"

时间:2016-01-06 20:17:39      阅读:341      评论:0      收藏:0      [点我收藏+]

标签:

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

 

LeetCode "Coin Change"

标签:

原文地址:http://www.cnblogs.com/tonix/p/5106607.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!