【发布时间】:2015-02-26 20:34:33
【问题描述】:
我有一些代码可以蛮力解决以下问题:
给定一组 x 个硬币和要达到的目标总和,达到该目标所需的最少硬币数量是多少?
到目前为止的代码:
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中使用循环进行计算组合?
如何迭代所有可能的组合?
【问题讨论】:
-
如果代码有效并且您只是在寻求改进,请转到codereview.stackexchange.com
-
“有什么办法吗?”是的。其他问题太笼统了,提到的代码审查网站是个好主意。
-
我确实发布了这个版本,但没有收到任何回复,所以我在这里寻求帮助 @markspace 我将编辑问题,然后使其不那么通用
-
可以重复硬币吗
-
@Amir 是的,您可以拥有无限数量的任何硬币,但如果您拥有超过 T/C 的硬币,它将超过目标,其中 T 是目标,c 是硬币值,例如。 T = 5, C = 2, 其中 5/2 = 2 在有效解中是最有可能的
标签: java optimization dynamic-programming