动态规划:负数完美求和

5

给定一个整数数组和一个目标和,任务是打印出所有元素之和等于目标和的子集。

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

    }   
} 

如何修改这段代码,使其适用于负数?


为什么“Can someone help me?”不是一个真正的问题? - Andy Turner
3个回答

1
你的解决方案假定所有值都是正数,因此动态规划数组“subset”填充了正数值的“j”,但现在需要考虑负和。
你需要做的是更改“j”的循环限制,以填充动态规划数组。
for (int j = negative_sum; j <= positive_sum; j++)

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

如需了解更多详情,请阅读子集和问题的维基百科页面此处,其中详细解释了这一步骤。


-1

由于您需要打印(或生成)给定集合(包含正整数和负整数)的所有可能子集,这些子集的总和等于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);
  }
}

谢谢你提供的解决方案。但我认为这有点暴力,因为我们需要遍历所有元素才能得到正确的子集。有没有办法可以使用动态规划来实现(即在伪多项式时间内)? - Somesh Dhal
由于我们必须打印出所有可能的子集,所以最少需要O(2 ^ n)的时间复杂度。谢谢! - BishalG

-1

您可以从数组中减去最小的负数,使数组中的数字变为正数。然后应用动态规划。


为什么,这是错的吗? - LetsGoBrandon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接