通过蛮力的爪哇硬币组合
我有一些代码可以用暴力解决以下问题:
Given a set of x coins and a target sum to reach, what is the fewest number of coins required to reach that target?
迄今为止的守则:
import java.util.ArrayList;
import java.util.Arrays;
public class coinsSum {
public static int min = Integer.MAX_VALUE;
public static int[] combination;
public static final int TARGET = 59;
public static void main(String[] args) {
long start = System.nanoTime();
int[] validCoins = new int[] {1, 2, 5, 10, 20};
Arrays.sort(validCoins);
int len = validCoins.length;
ArrayList<Integer> maxList = new ArrayList<Integer>();
for(int c : validCoins) {
maxList.add(TARGET / c);
}
int[] max = new int[len];
for(int i = 0; i < len; i++) {
max[i] = maxList.get(i).intValue();
}
permutations(new int[len], max, validCoins, 0); // bread&butter
if(min != Integer.MAX_VALUE) {
System.out.println();
System.out.println("The combination " + Arrays.toString(combination) + " uses " + min + " coins to make the target of: " + TARGET);
} else {
System.out.println("The target was not reachable using these coins");
}
System.out.println("TOOK: " + (System.nanoTime() - start) / 1000000 + "ms");
}
public static void permutations(int[] workspace, int[] choices, int[] coins, int pos) {
if(pos == workspace.length) {
int sum = 0, coinCount = 0;
System.out.println("TRYING " + Arrays.toString(workspace));
for(int a = 0; a < coins.length; a++) {
sum += workspace[a] * coins[a];
coinCount += workspace[a];
}
if(sum == TARGET) {
// System.out.println(Arrays.toString(n)); //valid combinations
if(coinCount < min) {
min = coinCount;
combination = workspace;
System.out.println(Arrays.toString(combination)+" uses " + min + " coins");
}
}
return;
}
for(int i = 0; i <= choices[pos]; i++) {
workspace[pos] = i;
permutations(workspace, choices, coins, pos + 1);
}
}
}
这个解决方案使用递归,有没有办法用循环在java中进行计算组合
除此之外,如何迭代所有可能的组合
# 1 楼答案
我发现了一种动态规划方法,这种方法肯定没有得到优化,但如果有人感兴趣的话,对于目标数字高达10000也不算太坏
# 2 楼答案
这里是python中的一个解决方案,它使用动态编程来找到达到目标值的最小硬币数
该算法的工作原理如下
因为对于每一枚硬币,你都在检查是否包含它,所以算法会枚举所有可能的组合
这是上述算法的空间优化版本
# 3 楼答案
您可以对硬币阵列进行排序。然后从右向左,不断从目标值中减去,直到硬币从目标的剩余值中变大。在硬币阵列中向左移动并重复此过程
例如: