简体   繁体   English

递归打印数组中等于给定总和的所有子集

[英]Print all subsets in an array that equal to a given sum recursively

I have to write a code with a two methods that takes an array (non-negative) and a value sum as parameters.我必须使用两种方法编写代码,将数组(非负)和值总和作为参数。 I have to use the methods:我必须使用以下方法:


public static void printSubsetSums(int[] arr, int sum) {

}

public static void printSubsetSums(int[] arr, int sum, int i, String acc) 
{

}

We are not allowed to add methods or any more parameters for the current methods.我们不允许为当前方法添加方法或任何更多参数。 I did something similar that just prints the number of subsets that are from a given array according to a sum.我做了类似的事情,只是根据总和打印来自给定数组的子集的数量。 but i'm having a hard time to change it to do this task... my array is limited to the length of 5.但我很难改变它来完成这项任务......我的数组被限制为 5 的长度。

ecxample: "Enter 5 numbers to array" input:1 2 3 4 5 "Enter a number into sum" input:8 3示例:“输入 5 个数字到数组”输入:1 2 3 4 5“输入一个数字到总和”输入:8 3

why 3?为什么3? (3,5), (1,3,4), (1,2,5) (3,5), (1,3,4), (1,2,5)

Thank you for your help!!!谢谢您的帮助!!!

Here is a recursive approach for solving this problem:这是解决此问题的递归方法:

    public static void printSubsetSums(int[] arr, int sum) {
        printSubsetSums(arr, sum, 0, "");
    }

    public static void printSubsetSums(int[] arr, int sum, int i, String acc) 
    {
        if (sum == 0 && !"".equals(acc)) {
            System.out.println(acc);
            acc = "";
        }
        if (i == arr.length) {
            return;
        }
        printSubsetSums(arr, sum, i + 1, acc);
        printSubsetSums(arr, sum - arr[i], i + 1, acc+" "+arr[i]);
    }

Explanation:解释:

First, you input your integer array and desired sum into the printSubsetSums(int[] arr, int sum) method that calls the helper method ( printSubsetSums(int[] arr, int sum, int i, String acc) ), where i is arr 's index and acc is the output for how the sum was reached.首先,您将 integer 数组和所需总和输入到调用辅助方法( printSubsetSums(int[] arr, int sum, int i, String acc) )的printSubsetSums(int[] arr, int sum)方法中,其中iarr的索引和acc是 output 如何达到总和。

if (i == arr.length) { return; } if (i == arr.length) { return; } acts as the base case to exit out of the recursive method ( i is out of bounds). if (i == arr.length) { return; }作为退出递归方法的基本情况( i超出范围)。

Notice that we have two recursive calls ( printSubsetSums(arr, sum, i + 1, acc) and printSubsetSums(arr, sum - arr[i], i + 1, acc+" "+arr[i]) ).请注意,我们有两个递归调用( printSubsetSums(arr, sum, i + 1, acc)printSubsetSums(arr, sum - arr[i], i + 1, acc+" "+arr[i]) )。 The first acts if the current number would not work in order to reach the sum and thus i is incremented to "try again" with the next number in arr .如果当前数字无法达到总和,则第一个动作,因此i将递增以使用arr中的下一个数字“重试”。 The second option is that the current number will work, and so you move on to the next index whilst accounting for the current number (subtracting it from sum in order to eventually reach 0 [when we know that the numbers selected did add up to 10] and adding it to acc ).第二个选项是当前数字将起作用,因此您在考虑当前数字的同时继续下一个索引(从sum中减去它以最终达到 0 [当我们知道所选数字确实加起来为 10 ] 并将其添加到acc )。

Finally, we print acc when the sum is 0. We also set acc = "" and avoid printing when "".equals(acc) in order to avoid counting the same answer multiple times.最后,我们在sum为 0 时打印acc 。我们还设置acc = ""并在"".equals(acc)时避免打印,以避免多次计算相同的答案。

Result:结果:

Example Input:示例输入:

printSubsetSums(new int[]{1,2,3,4,5}, 8)

Example Output:示例 Output:

 3 5
 1 3 4
 1 2 5

I think you have to take as input an array of numbers, and give the sum and number of integers that can be equal to this sum我认为你必须将一个数字数组作为输入,并给出可以等于这个总和的整数的总和和数量

In your example:在您的示例中:

Enter 5 numbers to array: 1 2 3 4 5输入 5 个数字进行排列:1 2 3 4 5

Enter a number into sum: 8 3 ( here i think 3 means it wants only 3 numbers to form 8, like 1 2 5 and 2 3 5 .. etc )在总和中输入一个数字:8 3(这里我认为 3 意味着它只需要 3 个数字来形成 8,例如1 2 52 3 5 .. 等)

You can do it in this way:你可以这样做:

public static void printSubsetSums(int[] arr, int sum, int i) {
    // getting all possible sub arrays of a lentgh of i 
    ArrayList<int[]> subarrays = new ArrayList<int[]>();
    ArrayList<Integer> array = new ArrayList<Integer>();


    int arrSize = arr.length;
    for (int startPoint = 0; startPoint <arrSize ; startPoint++) {
        for (int grps = startPoint; grps <=arrSize ; grps++) {
            for (int j = startPoint ; j < grps ; j++) {
                int element = arr[j];
                array.add(element);
            }
            int[] tab = new int[array.size()];
            int x = 0;
            for(int n : array) {
                tab[x] = n;
                x++;
            }
            subarrays.add(tab);
            array.clear();

        }
    }
    // calculating the sum of each one of these arrays
    // print the ones that their sum equal the sum given with argument
    for(int[] al : subarrays) {
        if (al.length==3) {
            int sum2 = 0;
            for (int n : al) {
                sum2 = sum2 + n;
                System.out.print(n);
            }
            System.out.print(" = "+sum2);
            if(sum2==sum) { System.out.print(" that is a desired sum"); }
            System.out.println();
        }
    }

}

The requirement imposed in the question is a little difficult to interpret.问题中强加的要求有点难以解释。 However, I have coded to fulfill your use case.但是,我已经编写代码来满足您的用例。

The approach which I have used is the following:我使用的方法如下:

  1. Find all the possible subset of the given array using the bit-manipulation method.使用位操作方法查找给定数组的所有可能子集。

  2. Check if the sum of the subset is equal to the given sum.检查子集的总和是否等于给定的总和。 If it is yes, then print it on the console.如果是,则在控制台上打印。

Check the snippet below for more clarity.检查下面的代码段以获得更清晰的信息。

import java.util.Scanner;

public class SubsetSum {
    public static void printSubsetSums(int[] arr, int sum) {
        printSubsetSums(arr, sum, 0, "NotNeeded");
    }

    public static void printSubsetSums(int[] arr, int sum, int i, String acc) {
        // variable 'i' and 'acc' are not getting used anywhere.
        // Have added because you want to make the same syntax for the function.
        boolean isAnySubsetPossible = false;
        int n = arr.length;

        // Run a loop from 0 to 2^n
        for (int p = 0; p < (1 << n); p++) {
            int[] temporaryArray = new int[n];
            int k = 0;
            int m = 1; // m is used to check set bit in binary representation.
            // Print current subset
            for (int j = 0; j < n; j++) {
                if ((p & m) > 0) {
                    temporaryArray[k++] = arr[j];
                }
                m = m << 1;
            }

            int localSum = 0;
            for (int temp : temporaryArray) {
                localSum += temp;
            }
            if (localSum == sum) { // check if the sum is equal to the desired sum
                isAnySubsetPossible = true;
                for (int item : temporaryArray) {
                    if (item > 0) {
                        System.out.print(item + " ");
                    }
                }
                // print a new line so that next subset starts from new line
                System.out.println();
            }
        }
        if (!isAnySubsetPossible) {
            System.out.println("There is no subset possible for the sum = " + 20);
        }
    }

    public static void main(String[] args) {
        Scanner myScanner = new Scanner(System.in);
        System.out.println("Enter 5 numbers into array");
        int[] myArr = new int[5];
        for (int i = 0; i < myArr.length; i++) {
            myArr[i] = myScanner.nextInt();
        }
        System.out.println("Enter a number into sum");
        int sum = myScanner.nextInt();
        printSubsetSums(myArr, sum);
    }
}

Input1 to the program程序的输入1

Enter 5 numbers into array
1 2 3 4 5
Enter a number into sum
8

Output1 by the program程序输出1

1 3 4 
1 2 5 
3 5

Input2 to the program程序的输入2

Enter 5 numbers into array
1 2 3 4 5
Enter a number into sum
20

Output2 by the program程序输出2

There is no subset possible for the sum = 20

I hope this helps.我希望这有帮助。

Suggest an algorithm or approach to print elements/integers of an array, given the sums of all subsets.给定所有子集的总和,建议一种算法或方法来打印数组的元素/整数。

For example, given sums of subset;例如,给定子集的总和; {0,1,2,3} --> values of the array would be, arr[] = {1,2}, whose subsets would be {{} -> sum is '0', {1} -> sum is '1', {2} -> sum is 2, {1,2} -> sum is '3'}; {0,1,2,3} --> 数组的值是 arr[] = {1,2},其子集是 {{} -> sum is '0', {1} -> sum是 '1', {2} -> sum 是 2, {1,2} -> sum 是 '3'}; Note: All values in the given array are positive N>=0;注意:给定数组中的所有值都是正数 N>=0;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 打印出一个递归等于给定和的数组中的所有子集 - Print out all subsets in an array that equal an given sum recursively 递归打印出等于给定总和的数组中的所有子集不会跳转到下一个迭代 - Print out all subsets in an array that equal an given sum recursively does not jump to the next iteration 以递归方式打印数组的所有子集 - Print all subsets of an array recursively 动态编程-打印给定总和的所有子集 - dynamic programming - print all subsets with the given sum 给定一个整数数组和一个总和,任务是找出给定数组的子集是否存在总和等于给定总和的子集 - Given an array of integers and a sum, the task is to find if there exists a subsets of given array with sum equal to given sum 使用数组中的前&#39;n&#39;个整数递归打印所有子集 - Recursively Print All Subsets Using First 'n' Integers in an Array 打印数组的所有子集 - Print all subsets of an array 给定一个数组,找到总和为值k的所有子集 - Given an array, find all subsets which sum to value k 回溯 - 给定一组数字,找到总和等于 M 的所有子集(给定 M) - Backtracking - Given a set of numbers, find all the subsets with a sum equal to M (M is given) 递归确定一组数字是否包含总和相等的两个子集 - Recursively determine if a set of numbers contains two subsets that equal in sum
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM