Leetcode|322. Change Exchange

Insert picture description here

1 Dynamic programming

The actual state transition equation is as follows:

dp[状态i] = min(1 + dp[状态i - 选择1], 1 + dp[状态i - 选择2], 1 + dp[状态i - 选择3],....);

Among them, how do we find the minimum of multiple elements? Is it the following

int maxNum = INT_MAX;
for (int i = 0; i < size; i++)
	maxNum = min(maxNum, num[i]);

So there is the mainstream expression of the state transition equation in the program

dp[状态i] = min(dp[状态i], 选择j);

The complete code is as follows

class Solution {
    
    
public:
    int coinChange(vector<int>& coins, int amount) {
    
    
        vector<int> dp(amount + 1, INT_MAX);
        // 1.base case
        dp[0] = 0; 
        // 2.状态
        for (int i = 1; i <= amount; i++) 
            // 3.选择
            for (auto& coin : coins) {
    
    
                if (i - coin < 0 || dp[i - coin] == INT_MAX) continue; // 因为不能有INT_MAX + 1
                // 4.状态转移
                dp[i] = min(dp[i], 1 + dp[i - coin]);
            }
        return (dp[amount] == INT_MAX) ? -1 : dp[amount];
    }
};

Insert picture description here

Guess you like

Origin blog.csdn.net/SL_World/article/details/114972578