Skip to content

Commit 9a51b46

Browse files
committed
Add solution for CoinChange
1 parent 2e166fd commit 9a51b46

1 file changed

Lines changed: 23 additions & 0 deletions

File tree

  • src/main/java/com/packt/datastructuresandalg/lesson4/activity/coinchange/solution
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package com.packt.datastructuresandalg.lesson4.activity.coinchange.solution;
2+
3+
public class CoinChange {
4+
public int ways(int N, int[] coins) {
5+
int[][] dp = new int[N + 1][coins.length + 1];
6+
for (int j = 0; j <= coins.length; j++)
7+
dp[0][j] = 1;
8+
for (int j = 1; j <= coins.length; j++) {
9+
for (int i = 1; i <= N; i++) {
10+
dp[i][j] = dp[i][j - 1];
11+
if (i - coins[j - 1] >= 0)
12+
dp[i][j] += dp[i - coins[j - 1]][j];
13+
}
14+
}
15+
return dp[N][coins.length];
16+
}
17+
18+
public static void main(String[] args) {
19+
int[] coins = {1, 2, 3};
20+
CoinChange cc = new CoinChange();
21+
System.out.println(cc.ways(4, coins));
22+
}
23+
}

0 commit comments

Comments
 (0)