LeetCode 518. Change Exchange II Dynamic Programming + Complete Backpack + Number of Combinations

You are given an array of integers  coins representing coins of different denominations, and another integer  amount representing the total amount. Please calculate and return the number of coin combinations that can make up the total amount. If no coin combination can add up to the total amount, return  0 .

Suppose there are an infinite number of coins of each denomination . The question data ensures that the result conforms to a 32-bit signed integer.

Example 1:

Input: amount = 5, coins = [1, 2, 5]
 Output: 4
 Explanation: There are four ways to make up the total amount:
5=5
5=2+2+1
5=2+1+1+1
5=1+1+1+1+1

Example 2:

Input: amount = 3, coins = [2]
 Output: 0
 Explanation: The total amount of 3 cannot be made up by using only coins of denomination 2.

Example 3:

Input: amount = 10, coins = [10] 
 Output: 1

>>Ideas and analysis

  • ① There is no limit to the number of coins, so you can know that this is a complete backpack problem;
  • ② What is the maximum value of a backpack that can be combined with a pure backpack? This question is about the number of combinations of items required to make up the total amount!

Note that the description of the question refers to the number of coin combinations that make up the total amount. Why is it emphasized that it is the number of combinations?

For example example one:

        5 = 2 + 2 + 1 

        5 = 2 + 1 + 2

This is a combination, both 2 2 1. If you are asking about the number of permutations, there are two permutations above.

Note: Combination does not emphasize the order between elements, while permutation emphasizes the order between elements.

>>Five Steps of Dynamic Rules

1. Determine the meaning of the dp array and subscripts

        dp[j]: The number of currency combinations that make up the total amount j is dp[j]

2. Determine the recursion formula

  •  dp[j] is the sum of all dp[j - coins[i]] (considering the case of coins[i])
  •  So the recursion formula: dp[j] += dp[j - coins[i]];

The 0-1 backpack question is explained in LeetCode 494. Goal He . There are several ways to fill the backpack, and the formulas are:

                                                        dp[j] += dp[j - nums[i]];

3.dp array initialization

dp[0] = 1, this is the basis of the recursive formula; if dp[0] = 0, all subsequent derived values ​​will be 0

dp[j] with a non-0 subscript is initialized to 0, so that the real dp[j] will not be affected when the cumulative addition of dp[j - coins[i]]

dp[0] = 1 also illustrates a situation: if coins[i] is selected, that is, j - coins[i] == 0 means that this coin can be selected, and dp[0] is 1 means there is such a selection method to only select coins[i]

4. Determine the traversal order

  • Method 1: Traverse the items first and then the backpack
  • Method 2: Traverse the backpack first and then traverse the items

In a pure complete backpack, it doesn't matter whether you traverse the items first and then the backpack, or you traverse the backpack first and then the items!

This question won’t work! Because the pure complete knapsack determines the maximum value of a full knapsack, it has nothing to do with whether the elements that make up the sum are in order, that is: it does not matter whether it is in order or not!

However, in this question, the number of combinations required to make up the sum is clearly required to be non-sequential among the elements. So it can only be the traversal order of method one, so why not method two?

For method 1 in a complete backpack: the outer for loop traverses the items (coins), and the inner for loop traverses the backpack (total money)

for (int i = 0; i < coins.size(); i++) { // 遍历物品
    for (int j = coins[i]; j <= amount; j++) { // 遍历背包容量
        dp[j] += dp[j - coins[i]];
    }
}

Assumption: coins[0] = 1,coins[1] = 5

Then add 1 to the calculation first, and then add 5 to the calculation. What you get is only the situation {1,5}, and the situation {5,1} will not occur, so in this traversal sequence dp[j] What is calculated here is the number of combinations!

For the second method in the complete backpack: the outer for loop traverses the backpack (total money), and the inner for loop loops through the items (coins)

for (int j = 0; j <= amount; j++) { // 遍历背包容量
    for (int i = 0; i < coins.size(); i++) { // 遍历物品
        if (j - coins[i] >= 0) dp[j] += dp[j - coins[i]];
    }
}

Each value of the backpack capacity is calculated by 1 and 5, including {1,5} and {5,1}. At this time, what is calculated in dp[j] is the number of permutations!

5. Derivation of dp array with examples

Input: amount = 5, coins = [1,2,5], the dp state diagram is as follows:

dp[amout] is the final result

class Solution {
public:
    int change(int amount, vector<int>& coins) {
        vector<int> dp(amount + 1, 0);
        dp[0] = 1;
        for (int i = 0; i < coins.size(); i++) { // 遍历物品
            for (int j = coins[i]; j <= amount; j++) { // 遍历背包
                dp[j] += dp[j - coins[i]];
            }
        }
        return dp[amount];
    }
};
  • Time complexity: O(mn), where m is the amount and n is the length of coins
  • Space complexity: O(m)

【Summarize】

The recursion formula of this question has been explained in detail in 494. Target Sum, and the difficulty of this question mainly lies in the traversal order!

  • When there are several options for filling a backpack, it is very critical to determine the order of traversal;
  • If you want to find the number of combinations , then the outer for loop traverses the items, and the inner for loop traverses the backpack.
  • If you want to find the number of permutations , the outer for loop traverses the backpack, and the inner for loop traverses the items.

Class screenshots from Code Caprice:

Reference articles and videos:

Code Random Record (programmercarl.com)

Complete knapsack of dynamic programming. How many ways are there to fill the knapsack? Pay attention to combination and arrangement! | LeetCode: 518. Change Exchange II_bilibili_bilibili

Guess you like

Origin blog.csdn.net/weixin_41987016/article/details/133381599