Coin change with limited number of coins

前端 未结 2 915
自闭症患者
自闭症患者 2020-12-11 19:05

I have written a program for generating subset sum which might be used in this problem which states:

Suppose, you have 3 $1-coins, 2 $2-coins, 3 $5

相关标签:
2条回答
  • 2020-12-11 19:32

    Let's assume all your ni are 1.

    Let ways[j] = number of ways of obtaining sum j.

    You can compute this like so (this is what you're doing, but I don't know why you named your variable primes).

    ways[0] = 1
    for i = 1 to m do
        for j = myLim downto X[i] do
            ways[j] += ways[j - X[i]];
    

    This means you only use each coin of value Xi once. You can add another loop to use it at least once and at most ni times however:

    ways[0] = 1
    for i = 1 to m do
        for times = 1 to n[i] do // use Xi one time, then two times, then three, ..., then ni
            for j = myLim downto times*X[i] do
                ways[j] += ways[j - times*X[i]];
    

    You can still apply your modulo and compute your limit, I left those out for simplicity.

    0 讨论(0)
  • 2020-12-11 19:43

    The problem is named "The coin problem" and is known to be NP-hard.

    You may learn a little about it here.

    0 讨论(0)
提交回复
热议问题