Backpack
92t Backpack
Given an array representing item size [2, 3, 5, 7], the backpack size is 11. Return the max size we can fill in the given backpack.
Use the package size as an array
1st loop the size array, second loop the volume from tail
State: dp[i][j]代表前i個item在j size下可以裝下的最大數字

Rolling array updates from tail
322 Coin Change
You are given coins of different denominations and a total amount of money amount. Write a function to compute 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
is computed as
dp[ ] initiate all max int
Coin 可以重複使用,outer loop coin 1~amount, inner loop 幣值
See example
518 Coin Change 2
You are given coins of different denominations and a total amount of money. Write a function to compute the number of combinations that make up that amount
Statment: dp[i][j]指前i種貨幣可以組成amount j 的方式個數
Func: dp[i][j] = dp[i-1][j] + dp[i][j-coin[i]] if j>=coin[i]
Init: dp[i][0] = 1
Ans dp[m+1][n+1]
1155. Number of Dice Rolls With Target Sum
You have d dice, and each die has f faces numbered 1, 2, ..., f.
Return the number of possible ways (out of fd total ways) modulo 10^9 + 7 to roll the dice so the sum of the face up numbers equals target.
Top-down DP
dp[i][j] = 在 i 個dice情況下達成 j 的combination
Runtime: O(d * f * target). Memory: O(d * target) for the memorization.
Bottom-Up DP
Similar to coin change, dp[i][j]為在提供 i number 的情況下可以得到 j 的combination, 注意 dp2[i][j] 受限於dp1[i-1][j] + dp1[i-1][j-1], 並且執行了 d 個 dice 次數
Runtime: O(d *f * target).
Memory: O(target) as we only store counts for the last dice.
Last updated
Was this helpful?