LeetMotion
You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.
Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.
One of the most teachable ways to understand DP is visualizing it as a road of jumps! Imagine a road of cells from 0 up to our target amount. The value inside each cell answers the question: What is the absolute minimum number of jumps needed to land exactly here?
dp[0] = 0 because it takes exactly 0 coins to make $0. Pre-fill the rest of the dp array with "infinity" (in code: amount + 1).a = 1, 2, 3.... At each target a, look backward: if (a - coin) >= 0, we can physically "jump" from that older cell!dp[a - coin] and add 1 (because the jump itself costs 1 coin!).dp[a]. Loop until dp[amount] is filled!
Discussion
…