我试图使用递归打印出与给定总和相等的所有子集。但是,我的代码在完成第一个代码后不会跳转到下一个迭代:
import java.util.*;
public class Combinations {
public static int currentSum = 0;
public static ArrayList<Integer> usedItems = new ArrayList<>();
public static void main( String[] args ) throws Exception {
int arr[] = {1, 2, 3, 4, 2};
int sum = 6;
printCombinations(arr, sum);
}
public static void printCombinations(int[] availableItems, int goal){
for (int i = 0; i < availableItems.length; i++){
if (currentSum + availableItems[i] == goal){
System.out.println(Arrays.toString(usedItems.toArray()) + availableItems[i]);
currentSum = 0;
usedItems.clear();
}
if(currentSum + availableItems[i] > goal){
continue;
}
if(currentSum + availableItems[i] < goal){
currentSum += availableItems[i];
usedItems.add(availableItems[i]);
int[] newAvailableItems = Arrays.copyOfRange(availableItems, 1, availableItems.length);
printCombinations(newAvailableItems, goal);
}
}
}
例如,如果总和等于6,程序只打印出1,2,3但不跳转到下一个数字并从那里检查。
答案 0 :(得分:0)
我认为问题在于:
if (currentSum + availableItems[i] == goal)
对于给定的数组int arr[] = {1, 2, 3, 4, 2};
和目标价值int sum = 6;
迭代:
currentSum = 0, availableItems[i] = 1
(0 + 1 = 1)适合 - &gt; if(currentSum + availableItems[i] < goal)
currentSum = 1, availableItems[i] = 2
(1 + 2 = 3)适合 - &gt; if(currentSum + availableItems[i] < goal)
currentSum = 3, availableItems[i] = 3
(3 + 3 = 6)适合 - &gt; if (currentSum + availableItems[i] == goal)
并在同一次迭代中:currentSum = 0, availableItems[i] = 3
(0 + 3 = 3)适合 - &gt; if (currentSum + availableItems[i] < goal)
currentSum = 3, availableItems[i] = 4
(3 + 4 = 7)
适合 - &gt; if(currentSum + availableItems[i] > goal)
等等...... 对于给定的数组,sum值不适合第一个,如果不是。
您需要增加迭代器:
if (currentSum + availableItems[i] == goal){
System.out.println(Arrays.toString(usedItems.toArray()) + availableItems[i]);
currentSum = 0;
usedItems.clear();
i++;
}