打印出一个数组中的所有子集,它们递归地等于给定的和不会跳转到下一次迭代

时间:2017-11-16 18:15:32

标签: java arrays recursion

我试图使用递归打印出与给定总和相等的所有子集。但是,我的代码在完成第一个代码后不会跳转到下一个迭代:

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但不跳转到下一个数字并从那里检查。

1 个答案:

答案 0 :(得分:0)

我认为问题在于:

 if (currentSum + availableItems[i] == goal)

对于给定的数组int arr[] = {1, 2, 3, 4, 2};和目标价值int sum = 6;

迭代:

  1. currentSum = 0, availableItems[i] = 1(0 + 1 = 1)适合 - &gt; if(currentSum + availableItems[i] < goal)
  2. currentSum = 1, availableItems[i] = 2(1 + 2 = 3)适合 - &gt; if(currentSum + availableItems[i] < goal)
  3. 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)
  4. currentSum = 3, availableItems[i] = 4(3 + 4 = 7) 适合 - &gt; if(currentSum + availableItems[i] > goal)等等......
  5. 对于给定的数组,sum值不适合第一个,如果不是。

    您需要增加迭代器:

    if (currentSum + availableItems[i] == goal){
        System.out.println(Arrays.toString(usedItems.toArray()) + availableItems[i]);
        currentSum = 0;
        usedItems.clear();
        i++;
    }