Given a list of coins[] representing different denominations, count all combinations of the coins to make a given value sum.
Building upon understanding of Find number of way to make coin change (Memoization). Tabulation essentially reconstructs the cache.
Start with the foundation – the base cases, which are the simplest solutions. Then, layer by layer, use the results of the previous layers to calculate the solutions for the next level. This way, we systematically build up the entire solution, avoiding redundant calculations and ensuring efficiency. It is like building a pyramid.
The underlying calculation logic remains fundamentally identical to the original recursive approach, albeit executed in reverse order.
def count(coins, total): cache = [[0 for _ in range(total + 1)] for _ in range(len(coins) + 1)] cache[0][0] = 1 for i in range(1, len(coins) + 1): for j in range(total + 1): cache[i][j] += cache[i - 1][j] if j >= coins[i - 1]: cache[i][j] += cache[i][j - coins[i - 1]] return cache[len(coins)][total] coins = [1, 2, 3] total = 4 print(count(coins, total))
function count(coins, sum) { const cache = []; for (let i = 0; i < coins.length + 1; i++) { cache[i] = Array(sum + 1).fill(0); } cache[0][0] = 1; for (let i = 1; i < coins.length + 1; i++) { for (let j = 0; j < sum + 1; j++) { cache[i][j] += cache[i - 1][j]; if (j >= coins[i - 1]) { cache[i][j] += cache[i][j - coins[i - 1]]; } } } return cache[coins.length][sum]; } const coins = [1, 2, 3]; const sum = 4; console.log(count(coins, sum));