首页 > 其他 > 详细

LeetCode "Coin Change"

时间:2016-01-06 20:14:39      阅读:150      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!