|
| 1 | +/* |
| 2 | +For the given infinite supply of coins of each of denominations, D = {D0, D1, D2, D3, ...... Dn-1}. |
| 3 | +You need to figure out the total number of ways W, in which you can make the change for Value V using coins of denominations D. |
| 4 | +Return 0 if the change isn't possible. |
| 5 | + |
| 6 | +Input Format |
| 7 | +The first line of the input contains an integer value N, which denotes the total number of denominations. |
| 8 | +The second line of input contains N values, separated by a single space. These values denote the value of denomination. |
| 9 | +The third line of the input contains an integer value, that denotes the value of V. |
| 10 | + |
| 11 | +Output Format |
| 12 | +Print the total total number of ways i.e. W. |
| 13 | + |
| 14 | +Constraints : |
| 15 | +1 <= n <= 10 |
| 16 | +1 <= V <= 1000 |
| 17 | +Time Limit: 1sec |
| 18 | + |
| 19 | +Sample Input 1 : |
| 20 | +3 |
| 21 | +1 2 3 |
| 22 | +4 |
| 23 | +Sample Output 1 : |
| 24 | +4 |
| 25 | +Explanation to Sample Input 1 : |
| 26 | +Number of ways are - 4 total i.e. (1,1,1,1), (1,1, 2), (1, 3) and (2, 2). |
| 27 | + |
| 28 | +Sample Input 2 : |
| 29 | +6 |
| 30 | +1 2 3 4 5 6 |
| 31 | +250 |
| 32 | +Sample Output 2 : |
| 33 | +13868903 |
| 34 | +*/ |
| 35 | + |
| 36 | +public class Solution { |
| 37 | + |
| 38 | + |
| 39 | + public static int countWaysToMakeChange(int denominations[], int value){ |
| 40 | + // Write your code here |
| 41 | + /* |
| 42 | + if (value==0) |
| 43 | + return 1; |
| 44 | + |
| 45 | + if (value<0) |
| 46 | + return 0; |
| 47 | + |
| 48 | + int finalAns=0; |
| 49 | + for (int i=0;i<denominations.length;i++) |
| 50 | + { |
| 51 | + finalAns=finalAns+countWaysToMakeChange(denominations,value-denominations[i]); |
| 52 | + } |
| 53 | + return finalAns; |
| 54 | + */ |
| 55 | + int[] dp = new int[value+1]; |
| 56 | + dp[0]=1; |
| 57 | + for (int i=0;i<denominations.length;i++) |
| 58 | + { |
| 59 | + for (int j=0;j<=value;j++) |
| 60 | + { |
| 61 | + if (j>=denominations[i]) |
| 62 | + { |
| 63 | + dp[j]=dp[j]+dp[j-denominations[i]]; |
| 64 | + } |
| 65 | + } |
| 66 | + } |
| 67 | + return dp[value]; |
| 68 | + } |
| 69 | +} |
0 commit comments