İçeriğe atla
ΣDSA Patterns
Menü
Dil

Knapsack ve Alt Küme DP

Rehber 4 / 6 · Yol 4 / 6

Bu yazı henüz İngilizce. Arayüz Türkçe; içerik çevirisi sürüyor.

Demo önizleme: Bu çözümler otomatik test paketini geçiyor ama insan tarafından incelenmedi. Trade-off ve yazıları taslak olarak değerlendirin.

Coin Change II

Problem (restated)

Number of combinations that make up amount with given coin denominations (order does not matter).

Intuition

Outer loop coins, inner amount ascending → combinations not permutations.

Approaches

Unbounded knapsack count

Tested only
Time O(amount · n)Space O(amount)

Idea. dp[0]=1; for coin: for a=coin..amount: dp[a]+=dp[a-coin].

Walkthrough. amount=5, coins=[1,2,5] → 4.

Trade-offs. Swap loop order → permutations (wrong for this problem).

Solution
export function change(amount: number, coins: number[]): number {
  const dp = new Array(amount + 1).fill(0);
  dp[0] = 1;
  for (const c of coins) {
    for (let a = c; a <= amount; a++) dp[a]! += dp[a - c]!;
  }
  return dp[amount]!;
}
export function change(amount: number, coins: number[]): number {
  const dp = new Array(amount + 1).fill(0);
  dp[0] = 1;
  for (const c of coins) {
    for (let a = c; a <= amount; a++) dp[a]! += dp[a - c]!;
  }
  return dp[amount]!;
}

Template connection

Knapsack unbounded combinations.

Reflection