Change Exchange (LeetCode 322)

The meaning of problems

Adequate number of coins of various denominations, how to use the least coin money designated Couchu

Thinking

This problem using dynamic programming problem solving. The current state is only related to the type of currency, it is a linear dynamic programming

Status Definitions:
DP [i]: i Couchu dollars minimum number required for the coin DP [i]

State transition equation:
DP [I] = min (DP [I - J], The value of J IS Coins)

Initial state:
DP [0] = 0

Code

class Solution {
public:
    int coinChange(vector<int>& coins, int amount) {
        if(amount == 0)
        {
            return 0;
        }
        vector<int> dp(amount+1, INT_MAX);
        dp[0] = 0;

        for(int i = 1; i <= amount; i++)
        {
            for(auto value : coins)
            {
                if(i - value >= 0)
                {
                    dp[i] = min(dp[i], dp[i-value]);
                }
                
            }
            if(dp[i] != INT_MAX)
                dp[i] += 1;
        }
        if(dp[amount] == INT_MAX)
            return -1;
        return dp[amount];

    }
};
// dp[i] : 凑齐i块钱,所需的硬币最小数量为dp[i]
// dp[i] = min(dp[i-j], j is the value of coins) + 1
// dp[0] = 0

Guess you like

Origin www.cnblogs.com/arcpii/p/12533838.html