Dynamic planning brush notes

Dynamic planning brushing notes (continuous update)

Principle of motion

Learning/Reference Video: [Dynamic Programming Special Class] ACM champion, Tsinghua University + Stanford God will guide
you to the dynamic programming algorithm

Solution steps

1. Determine the status

  • Determine the last step
  • Turned into sub-problems

2. Introduce the transfer equation
3. Determine the initial conditions and boundary conditions
4. Determine the calculation sequence

Practice list

Leetcode 322. Change Exchange

Title description:

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.
Example 1:
Input: coins = [1, 2, 5], amount = 11
Output: 3
Explanation: 11 = 5 + 5 + 1

Link to the original title:
Leetcode 322. Change Exchange

Problem-solving steps:
1. Determine the status

  • Determine the last step:
    In the case of the optimal strategy for this question, the face value of the last coin used is coins[i]
  • Turn into sub-problems:
    then this question can be transformed into using the least amount of coins to spell out (amount-coins[i])

2. Introduce the transfer equation

  • The value of the array f[x] represents the minimum number of coins required to spell out the amount X
  • f[x] = min{ f[x - coins[0]] + 1, f[x - coins[1]] + 1,…, f[x - coins[coins.size() - 1]] + 1 }

3. Judge the initial conditions and boundary conditions

  • f[0] = 0
  • If the coin of the current denomination cannot spell out the amount Y, then f[Y] = infinity

4. Determine the order of calculation

  • Calculate from f[1], calculate f[2], f[3], f[4]…f[amount] respectively, the final f[amount] is the answer to this question

Code display:

class Solution {
public:
    int coinChange(vector<int>& coins, int amount) {
        vector<int> res(amount+1);
        res[0] = 0;
        for(int i = 1; i <= amount; i++)
        {
            res[i] = INT_MAX;
            for(int j = 0; j < coins.size(); j++)
            {
                if(i >= coins[j] && res[i - coins[j]] != INT_MAX)
                {
                    res[i] = min(res[i - coins[j]] + 1, res[i]);
                }   
            }            
        }
        if(res[amount] == INT_MAX)
        {
            res[amount] = -1;
        }
        return res[amount];
    }
};

Time complexity analysis
Suppose there are coins of N denominations, and now you need to combine the amount M
to calculate f[1], f[2], f[3]...f[M], a total of M calculations
and each f[ The calculation of x] needs to use f[x-coins[0]], f[x-coins[1]]…f[x-coins[N-1]], a total of N times,
so a total of M * N The
time complexity of calculation is O(M * N)

Guess you like

Origin blog.csdn.net/NanlinW/article/details/115038440