我想用递归方法解决硬币更换问题。问题是这样的:硬币更换递归方法
给你不同面值的硬币和总金额。编写一个函数来计算构成该数量的组合的数量。
给你一定数量的硬币。
这是我到目前为止有:
private static int[] coins = {1,2,5};
public static void main(String[] args) {
System.out.println(count(13));
}
public static int count(int n)
{
// If n is 0 then there is 1 solution
if (n == 0)
return 1;
// If n is less than 0 then no solution exists
if (n < 0)
return 0;
return count(n - coins[0]) + count(n - coins[1]) + count(n - coins[2]);
}
当我做这个,我什么也没得到接近正确的组合。我认为这个问题与回归,但我不明白为什么。在这里,我从数量中减去硬币并每次将它们加在一起。当它变为0时,它返回1.
你会得到stackoverflow的错误,除非你改变它的一些...看着调用尾修剪,这是你存储的方法的价值在你计算的每个值,所以当你再次调用时,您只需查看数组而不是重新计算它。 –