Repository navigation
Expand file tree
/
Copy pathCoinChanging.java
More file actions
86 lines (77 loc) · 2.47 KB
/
Copy pathCoinChanging.java
File metadata and controls
86 lines (77 loc) · 2.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package com.interview.dynamic;
import java.util.ArrayList;
import java.util.List;
/**
* @Date 08/01/2014
* @author Tushar Roy
*
* Given a total and coins of certain denominations find number of ways total
* can be formed from coins assuming infinity supply of coins
*
* References:
* http://www.geeksforgeeks.org/dynamic-programming-set-7-coin-change/
*/
public class CoinChanging {
public int numberOfSolutions(int total, int coins[]){
int temp[][] = new int[coins.length+1][total+1];
for(int i=0; i <= coins.length; i++){
temp[i][0] = 1;
}
for(int i=1; i <= coins.length; i++){
for(int j=1; j <= total ; j++){
if(coins[i-1] > j){
temp[i][j] = temp[i-1][j];
}
else{
temp[i][j] = temp[i][j-coins[i-1]] + temp[i-1][j];
}
}
}
return temp[coins.length][total];
}
/**
* Space efficient DP solution
*/
public int numberOfSolutionsOnSpace(int total, int arr[]){
int temp[] = new int[total+1];
temp[0] = 1;
for(int i=0; i < arr.length; i++){
for(int j=1; j <= total ; j++){
if(j >= arr[i]){
temp[j] += temp[j-arr[i]];
}
}
}
return temp[total];
}
/**
* This method actually prints all the combination. It takes exponential time.
*/
public void printCoinChangingSolution(int total,int coins[]){
List<Integer> result = new ArrayList<>();
printActualSolution(result, total, coins, 0);
}
private void printActualSolution(List<Integer> result,int total,int coins[],int pos){
if(total == 0){
for(int r : result){
System.out.print(r + " ");
}
System.out.print("\n");
}
for(int i=pos; i < coins.length; i++){
if(total >= coins[i]){
result.add(coins[i]);
printActualSolution(result,total-coins[i],coins,i);
result.remove(result.size()-1);
}
}
}
public static void main(String args[]){
CoinChanging cc = new CoinChanging();
int total = 15;
int coins[] = {3,4,6,7,9};
System.out.println(cc.numberOfSolutions(total, coins));
System.out.println(cc.numberOfSolutionsOnSpace(total, coins));
cc.printCoinChangingSolution(total, coins);
}
}