240
笔下虽有千言,胸中实无一策

30 Day Challenge Day 20 | Leetcode 322. Coin Change

题解

Medium

Dynamic Programming

顺利做出来了。说明还是理解了coin的组合方式的。动态规划问题,很多都是排列组合问题的应用。

class Solution {
public:
    int coinChange(vector<int>& coins, int amount) {
        // dp[i]: with coins combine to amount of i
        // dp[i] = dp[k] + dp[i-k]
        
        vector<int> dp(amount+1, -1);
        
        dp[0] = 0;
        
        unordered_set<int> s(coins.begin(), coins.end());
        
        for(int i = 1; i < amount+1; i++) {
            for(int coin : coins) {
                if(i >= coin) {
                    if(dp[i-coin] == -1) continue;
                    if(dp[i] == -1) {
                        dp[i] = 1 + dp[i-coin];
                    }
                    else {
                        dp[i] = min(dp[i], 1 + dp[i - coin]);
                    }
                }
            }
        }
        
        return dp[amount];
    }
};
posted @ 2020-10-08 09:47  CasperWin  阅读(84)  评论(0编辑  收藏  举报