Let d[pos][sum] be the minimum number of coins needed to change money sum , using only the first pos denonyms or infinity, if this is not possible
Let a[i] denote coin i
This can be understood recursively. Rules 1) and 2) will be the basis of recursion.
1) d[any pos][0]=0 (We cannot return money without coins)
2) d[1][each sum] = if (a [1]! = Sum) Infinity else 1 (We can change the amount by one coin only if it has denomination sum )
3) Else:
We can select the current item to make changes or not select it
d[pos][sum]=min(choose,d[pos-1][sum]) where
choose=d[pos-1][sum-a[i]] if sum> = a [i], Infinity otherwise
If we do not select the pos coin number, we will try to do the same with the pos-1 coins. Therefore, d[pos-1][sum]
If we choose the coin number pos, then we only need to make a change for the amount that is less than the current by denominating pos. d[pos-1][sum-a[i]]
But we can choose the coin number pos only if its denunciation is less than or equal to the current amount
In real solution
a) Recursion should be replaced by a cycle
or
b) We must save was[pos][sum] - if the value d[pos][sum] has been calculated.
When we try to count d[pos][sum]
if was[pos][sum]==true will just return it. (The value has already been calculated)
else: count it according to steps 1-3 and set was[pos][sum] to true