Leetcode-322 Change Exchange Dynamic Planning DP

Given coins of different denominations and a total amount. Write a function to calculate the minimum number of coins required to make up the total amount. If no coin combination can make up the total amount, return -1.

You can think that the number of each coin is unlimited.

cpp implementation

class Solution {
    
    
public:
    int coinChange(vector<int>& coins, int amount) {
    
    

        // 方法一:动态规划
        // 等于钞票面值的最优解
        // 找出最小的i-coins[j]的金额就是最优解dp[i-coins[j]]+1
        // 1  2  5  7  10     //14
        //     0  1  2  3  4  5  6  7  8  9  10  11  12  13
        // dp  0  1  1  2  2  1  2  1  2  2  1   2   3   2
        
        // 初始化数组dp, 大小是amount+1, 全部元素初始化为-1
        vector<int> dp(amount+1, -1);
        // 金额0的最优解dp[0]=0
        dp[0] = 0;
        // 变量i从1循环到amount,一次计算金额1到amount的最优解
        for(int i=1; i<=amount; i++){
    
    
            // 对于每一个金额i, 使用变量j遍历面值c
            for(int j=0; j<coins.size(); j++){
    
    
                // 所有与小于等于i的面值coins[j], 如果金额i-coins[j]有最优解
                if(coins[j]<=i && dp[i-coins[j]]!=-1){
    
    
                    // 如果当前金额还未计算或者dp[i]比正在计算的最优解大(避免重复计算)
                    if(dp[i]==-1||dp[i]>dp[i-coins[j]]+1){
    
    
                        // 更新dp[i]
                        dp[i] = dp[i-coins[j]] + 1;
                    }
                }
            }
        }
        return dp[amount];
    }
};

py implementation

class Solution:
    def coinChange(self, coins: List[int], amount: int) -> int:
        # 初始化dp数组为-1
        dp = []
        for i in range(amount+1):
            dp.append(-1)
        dp[0] = 0
        
        # 遍历变量i从1到amount,依次计算金额1到amount的最优解
        for i in range(1, amount+1):
            for j in range(len(coins)):
                if coins[j] <= i and dp[i-coins[j]] != -1:
                    if dp[i] == -1 or dp[i] > dp[i-coins[j]]+1:
                        dp[i] = dp[i-coins[j]] + 1
        return dp[amount]

Source of test questions: LeetCode
Link: https://leetcode-cn.com/problems/coin-change

Guess you like

Origin blog.csdn.net/weixin_40437821/article/details/114190056