Try to understand the algorithm using this method.
table[i][j] means using the first i types of coins to change the value of j . then:
table[i][j] = table[i-1][j] + table[i][jS[i]]
Clearly, when creating coins j , you have two options. not using the i-th coin or using the i-th coin. When the ith coin is not used, the solution number is table[i-1][j] . When using the i-th coin, the solution number is table[i][jS[i]] , which means using the first i coins to create the value jS [i]. Therefore, the sum is the sum of both, which is table[i-1][j] + table[i][jS[i]]
In the code, you will see a for loop. the outer loop iterates over i and the inner loop repeats over j. the += operator computes table[i][j] based on the equation above.
EDIT
table[j] in your code is actually table[i][j] , which I am talking about above, and i is the value in your loop. after the cycle table[N] means table[M][N] , representing the use of the first coins of M , which are all coins, to make a value for N
I will talk in more detail based on the code:
for(int i=0; i<m; i++) for(int j=S[i]; j<=n; j++) table[j] += table[jS[i]];
When i = 0 , table[j] means using the first 1 coins to make changes to the j value. for example, table[2] now means using coins {1} to change to 2. So:
table[1] = table[1] + table[1 - S[0]] = table[1] + table[0] = 1 + 0= 1 table[2] = table[2] + table[2 - S[0]] = table[2] + table[1] = 0 + 1= 1 table[3] = 1 table[4] = 1
After that, we got the results when I = 0. table[1] ~ table[4] now means using coin {1} to make changes for values ββ1, 2, 3, 4 separately.
When i = 1, table[j] means using coin {1, 2} to make changes to the value of j .
table[2] = table[2] + table[2 - S[1]] = table[2] + table[0] = 1 + 1= 2 table[3] = table[3] + table[3 - S[1]] = 1 + 1 = 2 table[4] = table[4] + table[4 - S[1]] = table[4] + table[2] = 1 + 2 = 3
The next process is the same.
Finally, we take table[4] when i = 1 exit and analyze it:
table[4] = table[4] + table[4 - S[1]] = table[4] + table[2] = 1 + 2 = 3
Here table[4] on the left is the value that we are calculating and actually it is table[i=1][4] . table[4] on the right represents the previous value and in this case table[i=0][4] . It can expand to:
table[i=1][4] = table[i=0][4] + table[i=1][4 - S[1]]
equation for sure
table[i][j] = table[i-1][j] + table[i][jS[i]]
EDIT Follow up question
If you think you really understand this question, try to solve the same problem with a new restriction. What if each coin can be used only once? For example, N = 4 and S = {1,2,3}, only one solution is {1,3}, so the output should be 1. And for N = 10 and S = {2, 5, 3, 6} another solution is {2, 3, 5}, and the output is 1.
Hint: just one change to the source code is enough.
Answer: http://ideone.com/t1JnEz