//inefficient recursive algorithm to find number of coins needed for a some amount
public class bitcoin {
public int mincoins;
public static void main(String[] args) {
int[] coins = {1, 5, 10, 21, 25};
int change = 63;
int min = 0;
min = MinCoins(coins, change);
System.out.println(min);
}
public static int MinCoins(int[] coins, int change) {
int mincoins = change;
int mincoins1 = 10000;
for (int j = 0; j <= coins.length - 1; j++) {
if (coins[j] == change) //base case
return 1;
}
//recursive call breaking into two sub problems
for (int i = 1; i <= (change) / 2; i++) {
mincoins1 = (MinCoins(coins, i) + MinCoins(coins, (change - i)));
if (mincoins1 < change)
mincoins = mincoins1;
}
return mincoins;
}
}
答案 0 :(得分:0)
正如您的评论所暗示的,这是一种效率低下的递归算法。但是通过稍微移动代码,至少不会永远循环。相反,它最终找到了一个解决方案(对于我所做的所有测试,它已经找到了最佳的硬币数量。)
您错过的部分是退出失败标准。在这个例子中:
If the coin sum is more than 'change', give up.
(For example, if you have already added 3 coins with value 25 (total 75), there are no
coins that can help you reach 63, so stop trying to find them.)
此if语句(见下文)处理退出失败:
if (change - coins[j] >= 0)
public static int MinCoins(int[] coins, int change) {
int mindepth = 10000;
for (int j = 0; j < coins.length; j++) {
if (coins[j] == change) {
return 1; // end case
} else if (change - coins[j] >= 0) {
int depth = 1 + MinCoins(coins, change - coins[j]);
if (depth >= 0 && depth < mindepth) {
mindepth = depth;
}
}
}
return mindepth;
}