简体   繁体   中英

Print out all subsets in an array that equal an given sum recursively does not jump to the next iteration

I'm trying to print out all the subsets that is equal to a given sum using recursion. However, my code doesn't jump to the next iteration after the first one is finished:

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);
        }
    }
}

For example if the sum equals 6 the program only prints out 1, 2, 3 but not jump to the next number and check from there.

I think the problem is here:

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

For the given array int arr[] = {1, 2, 3, 4, 2}; and goal value int sum = 6;

Iterations:

  1. currentSum = 0, availableItems[i] = 1 (0 + 1 = 1) fits -> if(currentSum + availableItems[i] < goal)
  2. currentSum = 1, availableItems[i] = 2 (1 + 2 = 3) fits -> if(currentSum + availableItems[i] < goal)
  3. currentSum = 3, availableItems[i] = 3 (3 + 3 = 6) fits -> if (currentSum + availableItems[i] == goal) and in the same iteration: currentSum = 0, availableItems[i] = 3 (0 + 3 = 3) fits -> if (currentSum + availableItems[i] < goal)
  4. currentSum = 3, availableItems[i] = 4 (3 + 4 = 7) fits -> if(currentSum + availableItems[i] > goal) and so on...

For the given array and sum value is not going to fit the first if never.

You need increase the iterator:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM