C++ DP solution


  • 0
    class Solution {
    public:
        int coinChange(vector<int>& coins, int amount) {
            sort(coins.begin(), coins.end());
            vector<int> dp(amount + 1, INT_MAX); dp[0] = 0;
            for (int i = 1; i <= amount; ++i) {
                for (auto &coin : coins) {
                    if (coin > i) break;
                    if (dp[i - coin] == INT_MAX) continue;
                    dp[i] = std::min(dp[i], dp[i - coin] + 1);
                }
            }
            return dp[amount] == INT_MAX ? -1 : dp[amount];
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.