 Open in App
Not now

# PHP Program for Coin Change | DP-7

• Last Updated : 19 Jan, 2022

Given a value N, if we want to make change for N cents, and we have infinite supply of each of S = { S1, S2, .. , Sm} valued coins, how many ways can we make the change? The order of coins doesn\’t matter.

For example, for N = 4 and S = {1,2,3}, there are four solutions: {1,1,1,1},{1,1,2},{2,2},{1,3}. So output should be 4. For N = 10 and S = {2, 5, 3, 6}, there are five solutions: {2,2,2,2,2}, {2,2,3,3}, {2,2,6}, {2,3,5} and {5,5}. So the output should be 5.

## Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution.

Following is a simple recursive implementation of the Coin Change problem.

## PHP

 `= 1)` `        ``return` `0;`   `    ``// count is sum of solutions (i) ` `    ``// including S[m-1] (ii) excluding S[m-1]` `    ``return` `coun(``\$S``, ``\$m` `- 1,``\$n` `) + ` `           ``coun(``\$S``, ``\$m``, ``\$n` `- ``\$S``[``\$m` `- 1] );` `}`   `    ``// Driver Code` `    ``\$arr` `= ``array``(1, 2, 3);` `    ``\$m` `= ``count``(``\$arr``);` `    ``echo` `coun(``\$arr``, ``\$m``, 4); ` `    `  `// This code is contributed by Sam007` `?>`

## PHP

 `= 0) ? ` `                  ``\$table``[``\$i` `- ``\$S``[``\$j``]][``\$j``] : 0;`   `            ``// Count of solutions` `            ``// excluding S[j]` `            ``\$y` `= (``\$j` `>= 1) ? ` `                  ``\$table``[``\$i``][``\$j` `- 1] : 0;`   `            ``// total count` `            ``\$table``[``\$i``][``\$j``] = ``\$x` `+ ``\$y``;` `        ``}` `    ``}` `    ``return` `\$table``[``\$n``][``\$m``-1];` `}`   `// Driver Code` `\$arr` `= ``array``(1, 2, 3);` `\$m` `= ``count``(``\$arr``);` `\$n` `= 4;` `echo` `count1(``\$arr``, ``\$m``, ``\$n``);`   `// This code is contributed by mits` `?>`

Following is a simplified version of method 2. The auxiliary space required here is O(n) only.

## PHP

 ``

Please refer complete article on Coin Change | DP-7 for more details!

My Personal Notes arrow_drop_up
Related Articles