动态编程:负数的完美总和

问题描述 投票:4回答:3

给定一个整数数组和一个和,任务是打印给定数组的所有子集,其总和等于给定的总和。

Example: 
Input : arr[] = {1, 2, 3, 4, 5}
        sum = 10
Output : [4 3 2 1]  
         [5 3 2] 
         [5 4 1]

Input : arr[] = {-1, 2, 3, 4, 5}
        sum = 10
Output : [5 3 2] 
         [5 4 2 -1]

我在伪多项式时间内使用动态编程完成了这项工作。这是子集和问题的扩展,其仅负责决定是否存在这样的子集。我的解决方案适用于子集求和问题的正数和负数。但是,如果数组包含负数,则无法正确打印子集。程序是 -

import java.util.ArrayList;

// sum problem
class GFG {

    static boolean subset[][];

    // Returns true if there is a subset of
    // set[] with sun equal to given sum
    static boolean isSubsetSum(int set[],
                               int n, int sum) {
        // The value of subset[i][j] will be
        // true if there is a subset of
        // set[0..j-1] with sum equal to i
        subset = new boolean[n + 1][sum + 1];

        // Fill the subset table in botton
        // up manner
        for (int i = 0; i <= n; i++) {
            for (int j = 0; j <= sum; j++) {
                if (j == 0) {
                    subset[i][j] = true;
                } else if (i <= 0 && sum >= 1)
                    subset[i][j] = false;
                else if (set[i - 1] > j)
                    subset[i][j] = subset[i - 1][j];
                else {
                    if (set[i - 1] >= 0)
                        subset[i][j] = subset[i - 1][j] || subset[i - 1][j - set[i - 1]];
                    else
                        subset[i][j] = subset[i - 1][j] || subset[i - 1][j + set[i - 1]];
                }
            }
        }

        // uncomment this code to print table
//        for (int i = 0; i <= sum; i++)
//        {
//        for (int j = 0; j <= n; j++)
//            System.out.println (subset[i][j]);
//        }

        return subset[n][sum];
    }

    /* Driver program to test above function */
    public static void main(String args[]) {
        int set[] = {1, 2, 3, 4, 5};
        int sum = 10;
        int n = set.length;
        if (isSubsetSum(set, n, sum) == true)
            System.out.println("Found a subset"
                    + " with given sum");
        else
            System.out.println("No subset with"
                    + " given sum");
        System.out.println("Done");
        ArrayList<Integer> list = new ArrayList<>();
        printSubsets(set, n, sum, list);
        System.out.println("Finished");
    }

    static void display(ArrayList<Integer> v) {
        System.out.println(v);
    }

    private static void printSubsets(int[] set, int i, int sum, ArrayList<Integer> list) {
        if (i == 0 && sum != 0 && subset[0][sum]) {
            list.add(set[i]);
            display(list);
            list.clear();
            return;
        }

        // If sum becomes 0
        if (i == 0 && sum == 0) {
            display(list);
            list.clear();
            return;
        }

        // If given sum can be achieved after ignoring
        // current element.
        if (subset[i - 1][sum]) {
            // Create a new vector to store path
            ArrayList<Integer> b = new ArrayList<>();
            b.addAll(list);
            printSubsets(set, i - 1, sum, b);
        }

        // If given sum can be achieved after considering
        // current element.

        if (sum >= set[i - 1] && subset[i - 1][sum - set[i - 1]]) {
            list.add(set[i - 1]);
            printSubsets(set, i - 1, sum - set[i - 1], list);
        }

    }   
} 

如何修改此代码以适用于负数?

java data-structures dynamic-programming subset-sum
3个回答
0
投票

由于您必须打印(或生成)给定集合的所有可能子集(包含正整数和负整数),其总和等于sum,您可以做的是:

尝试将集合的每个位置表示为0和1的二进制表示,其中1表示采用该位置的元素,0表示不考虑该位置的元素。

找到有1的所有位置的总和。如果这些值的总和恰好等于给定的总和,则打印该子集。

所以,总的时间复杂度是O(2 ^ n),其中n是给定集的长度。

您可以查看以下实现。

import java.util.Arrays;

public class PerfectSum {

public static void printSubsets(int[] set, int n, int sum) {
     int totalSubSets = (1 << n);
     for (int i = 1; i < totalSubSets; ++i) { // loop over all possible subsets
         int curSum = 0;
         for (int j = n - 1; j >= 0; --j) {
             if (((i >> j) & 1) > 0) { // if bit at jth position is 1 take that value
                curSum +=set[j];
             }
         }
         if (curSum == sum) { // valid subset found, then print it
             for (int j = n - 1; j >= 0; --j) { // looping in reverse order to print set in decreasing order
                 if (((i >> j) & 1) > 0) { // if bit at jth position is 1 take that value
                     System.out.print(set[j] + " ");
                 }
             }
             System.out.println("");
         }
     }
}

public static void main(String[] args) {
    int set[] = {-1, 2, 3, 4, 5};
    Arrays.sort(set); // To print in non increasing order
    int sum = 10;
    int n = set.length;
    printSubsets(set, n, sum);
  }
}

0
投票

您的解决方案假设所有值都是正数,因此动态编程数组subset填充了正数的j值,但您现在需要考虑负数。

您需要做的是更改j的循环限制以填充动态编程数组

for (int j = negative_sum; j <= positive_sum; j++)

其中negative_sum是所有负值的总和,positive_sum是所有正值的总和。

有关更多详细信息,请阅读维基百科页面,了解子步骤求和问题here,其中解释了此步骤。


-1
投票

您可以将数组的最小负数减去整个集合,使数组中的数字为正数。然后应用动态编程。

© www.soinside.com 2019 - 2024. All rights reserved.