Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number of ways to add up to a sum S with N numbers

Say S = 5 and N = 3 the solutions would look like - <0,0,5> <0,1,4> <0,2,3> <0,3,2> <5,0,0> <2,3,0> <3,2,0> <1,2,2> etc etc.

In the general case, N nested loops can be used to solve the problem. Run N nested loop, inside them check if the loop variables add upto S.

If we do not know N ahead of time, we can use a recursive solution. In each level, run a loop starting from 0 to N, and then call the function itself again. When we reach a depth of N, see if the numbers obtained add up to S.

Any other dynamic programming solution?

like image 878
Hari Sundararajan Avatar asked Jan 03 '11 21:01

Hari Sundararajan


2 Answers

Try this recursive function:

f(s, n) = 1                                    if s = 0
        = 0                                    if s != 0 and n = 0
        = sum f(s - i, n - 1) over i in [0, s] otherwise

To use dynamic programming you can cache the value of f after evaluating it, and check if the value already exists in the cache before evaluating it.

like image 105
Mark Byers Avatar answered Nov 16 '22 00:11

Mark Byers


There is a closed form formula : binomial(s + n - 1, s) or binomial(s+n-1,n-1)

Those numbers are the simplex numbers.

If you want to compute them, use the log gamma function or arbitrary precision arithmetic.

See https://math.stackexchange.com/questions/2455/geometric-proof-of-the-formula-for-simplex-numbers

like image 29
Alexandre C. Avatar answered Nov 16 '22 02:11

Alexandre C.