cannot find the problem, everytime when I'm running this code it goes stackoverflow due to this line
countCombine += count(array,money - (array[i]*(int)(money/array[i])));
basically problem is very easy. 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.
public class CoinExchangeProblem {
int countCombine = 0;
private int count(int array[],int money){
// sort the array
// Arrays.sort(array);
// System.out.println(Arrays.toString(array));
if (money == 0) {
return 1;
} else if (money < 0) {
return 0;
}
for(int i = 0; i < array.length; i++){
countCombine += count(array,money - (array[i]*(int)(money/array[i])));
}
return countCombine;
}
public static void main(String[] args) {
CoinExchangeProblem coinExch = new CoinExchangeProblem();
System.out.println(coinExch.count(new int[]{1,2,3}, 4));
// System.out.println(coinExch.count(new int[]{2, 5, 3, 6}, 10));
}
}