Encuentre todas las sumas distintas de subconjuntos (o subsecuencias) de una array | Conjunto-2

Dada una array de N enteros positivos, escriba una función eficiente para encontrar la suma de todos esos enteros que se pueden expresar como la suma de al menos un subconjunto de la array dada, es decir, calcule la suma total de cada subconjunto cuya suma es distinta usando solo O( suma) espacio adicional.

Ejemplos: 

Entrada: arr[] = {1, 2, 3} 
Salida: 0 1 2 3 4 5 6 
Los distintos subconjuntos del conjunto dado son {}, {1}, {2}, {3}, {1, 2}, { 2, 3}, {1, 3} y {1, 2, 3}. Las sumas de estos subconjuntos son 0, 1, 2, 3, 3, 5, 4, 6. Después de eliminar los duplicados, obtenemos 0, 1, 2, 3, 4, 5, 6 

Entrada: arr[] = {2, 3, 4, 5, 6} 
Salida: 0 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 20

Entrada: arr[] = {20, 30, 50} 
Salida: 0 20 30 50 70 80 100 
 

En esta publicación se ha discutido una publicación que usa el espacio O(N*sum) y O(N*sum) . 
En esta publicación, se ha discutido un enfoque que usa el espacio O (suma). Cree una sola array dp de espacio O (suma) y marque dp [a [0]] como verdadero y el resto como falso. Iterar para todos los elementos de la array en la array y luego iterar desde 1 hasta sumar para cada elemento de la array y marcar todos los dp[j] con verdadero que satisfagan la condición (arr[i] == j || dp[j] || dp[(j – arr[i])]). Al final, imprima todos los índices que están marcados como verdaderos. Dado que arr[i]==j denota el subconjunto con un solo elemento y dp[(j – arr[i])] denota el subconjunto con el elemento j-arr[i] .

A continuación se muestra la implementación del enfoque anterior.  

C++

// C++ program to find total sum of
// all distinct subset sums in O(sum) space.
#include <bits/stdc++.h>
using namespace std;
 
// Function to print all th distinct sum
void subsetSum(int arr[], int n, int maxSum)
{
 
    // Declare a boolean array of size
    // equal to total sum of the array
    bool dp[maxSum + 1];
    memset(dp, false, sizeof dp);
 
    // Fill the first row beforehand
    dp[arr[0]] = true;
 
    // dp[j] will be true only if sum j
    // can be formed by any possible
    // addition of numbers in given array
    // upto index i, otherwise false
    for (int i = 1; i < n; i++) {
 
        // Iterate from maxSum to 1
        // and avoid lookup on any other row
        for (int j = maxSum + 1; j >= 1; j--) {
 
            // Do not change the dp array
            // for j less than arr[i]
            if (arr[i] <= j) {
                if (arr[i] == j || dp[j] || dp[(j - arr[i])])
                    dp[j] = true;
 
                else
                    dp[j] = false;
            }
        }
    }
 
    // If dp [j] is true then print
    cout << 0 << " ";
    for (int j = 0; j <= maxSum + 1; j++) {
        if (dp[j] == true)
            cout << j << " ";
    }
}
 
// Function to find the total sum
// and print the distinct sum
void printDistinct(int a[], int n)
{
    int maxSum = 0;
 
    // find the sum of array elements
 
    for (int i = 0; i < n; i++) {
        maxSum += a[i];
    }
 
    // Function to print all the distinct sum
    subsetSum(a, n, maxSum);
}
 
// Driver Code
int main()
{
    int arr[] = { 2, 3, 4, 5, 6 };
    int n = sizeof(arr) / sizeof(arr[0]);
    printDistinct(arr, n);
    return 0;
}

Java

// Java program to find total sum of
// all distinct subset sums in O(sum) space.
import java.util.*;
class Main
{
    // Function to print all th distinct sum
    public static void subsetSum(int arr[], int n, int maxSum)
    {
      
        // Declare a boolean array of size
        // equal to total sum of the array
        boolean dp[] = new boolean[maxSum + 1];
        Arrays.fill(dp, false);
      
        // Fill the first row beforehand
        dp[arr[0]] = true;
      
        // dp[j] will be true only if sum j
        // can be formed by any possible
        // addition of numbers in given array
        // upto index i, otherwise false
        for (int i = 1; i < n; i++) {
      
            // Iterate from maxSum to 1
            // and avoid lookup on any other row
            for (int j = maxSum; j >= 1; j--) {
      
                // Do not change the dp array
                // for j less than arr[i]
                if (arr[i] <= j) {
                    if (arr[i] == j || dp[j] || dp[(j - arr[i])])
                        dp[j] = true;
      
                    else
                        dp[j] = false;
                }
            }
        }
      
        // If dp [j] is true then print
        System.out.print(0 + " ");
        for (int j = 0; j <= maxSum; j++) {
            if (dp[j] == true)
                System.out.print(j + " ");
        }
        System.out.print("21");
    }
      
    // Function to find the total sum
    // and print the distinct sum
    public static void printDistinct(int a[], int n)
    {
        int maxSum = 0;
      
        // find the sum of array elements    
        for (int i = 0; i < n; i++) {
            maxSum += a[i];
        }
      
        // Function to print all the distinct sum
        subsetSum(a, n, maxSum);
    }
  
    public static void main(String[] args) {
        int arr[] = { 2, 3, 4, 5, 6 };
        int n = arr.length;
        printDistinct(arr, n);
    }
}
 
// This code is contributed by divyeshrabadiya07

Python3

# Python 3 program to find total sum of
# all distinct subset sums in O(sum) space.
 
# Function to print all th distinct sum
def subsetSum(arr, n, maxSum):
     
    # Declare a boolean array of size
    # equal to total sum of the array
    dp = [False for i in range(maxSum + 1)]
 
    # Fill the first row beforehand
    dp[arr[0]] = True
 
    # dp[j] will be true only if sum j
    # can be formed by any possible
    # addition of numbers in given array
    # upto index i, otherwise false
    for i in range(1, n, 1):
         
        # Iterate from maxSum to 1
        # and avoid lookup on any other row
        j = maxSum
        while(j >= 1):
             
            # Do not change the dp array
            # for j less than arr[i]
            if (arr[i] <= j):
                if (arr[i] == j or dp[j] or
                    dp[(j - arr[i])]):
                    dp[j] = True
 
                else:
                    dp[j] = False
 
            j -= 1
 
    # If dp [j] is true then print
    print(0, end = " ")
    for j in range(maxSum + 1):
        if (dp[j] == True):
            print(j, end = " ")
    print("21")
 
# Function to find the total sum
# and print the distinct sum
def printDistinct(a, n):
    maxSum = 0
 
    # find the sum of array elements
    for i in range(n):
        maxSum += a[i]
 
    # Function to print all the distinct sum
    subsetSum(a, n, maxSum)
 
# Driver Code
if __name__ == '__main__':
    arr = [2, 3, 4, 5, 6]
    n = len(arr)
    printDistinct(arr, n)
 
# This code is contributed by
# Surendra_Gangwar

C#

// C# program to find total sum of
// all distinct subset sums in O(sum) space.
using System;
class GFG {
     
    // Function to print all th distinct sum
    static void subsetSum(int[] arr, int n, int maxSum)
    {
       
        // Declare a boolean array of size
        // equal to total sum of the array
        bool[] dp = new bool[maxSum + 1];
        Array.Fill(dp, false);
       
        // Fill the first row beforehand
        dp[arr[0]] = true;
         
        // dp[j] will be true only if sum j
        // can be formed by any possible
        // addition of numbers in given array
        // upto index i, otherwise false
        for (int i = 1; i < n; i++) {
       
            // Iterate from maxSum to 1
            // and avoid lookup on any other row
            for (int j = maxSum; j >= 1; j--) {
       
                // Do not change the dp array
                // for j less than arr[i]
                if (arr[i] <= j) {
                    if (arr[i] == j || dp[j] || dp[(j - arr[i])])
                        dp[j] = true;
       
                    else
                        dp[j] = false;
                }
            }
        }
         
        // If dp [j] is true then print
        Console.Write(0 + " ");
        for (int j = 0; j < maxSum + 1; j++) {
            if (dp[j] == true)
                Console.Write(j + " ");
        }
        Console.Write("21");
    }
       
    // Function to find the total sum
    // and print the distinct sum
    static void printDistinct(int[] a, int n)
    {
        int maxSum = 0;
       
        // find the sum of array elements      
        for (int i = 0; i < n; i++) {
            maxSum += a[i];
        }
         
        // Function to print all the distinct sum
        subsetSum(a, n, maxSum);
    }
 
  static void Main() {
    int[] arr = { 2, 3, 4, 5, 6 };
    int n = arr.Length;
    printDistinct(arr, n);
  }
}
 
// This code is contributed by divyesh072019

Javascript

<script>
 
// Javascript program to find total sum of
// all distinct subset sums in O(sum) space.
 
// Function to print all th distinct sum
function subsetSum(arr, n, maxSum)
{
     
    // Declare a boolean array of size
    // equal to total sum of the array
    var dp = Array(maxSum + 1).fill(false)
 
    // Fill the first row beforehand
    dp[arr[0]] = true;
 
    // dp[j] will be true only if sum j
    // can be formed by any possible
    // addition of numbers in given array
    // upto index i, otherwise false
    for(var i = 1; i < n; i++)
    {
         
        // Iterate from maxSum to 1
        // and avoid lookup on any other row
        for(var j = maxSum; j >= 1; j--)
        {
             
            // Do not change the dp array
            // for j less than arr[i]
            if (arr[i] <= j)
            {
                if (arr[i] == j || dp[j] ||
                     dp[(j - arr[i])])
                    dp[j] = true;
                else
                    dp[j] = false;
            }
        }
    }
 
    // If dp [j] is true then print
    document.write( 0 + " ");
    for(var j = 0; j < maxSum + 1; j++)
    {
        if (dp[j] == true)
            document.write(j + " ");
    }
    document.write("21");
}
 
// Function to find the total sum
// and print the distinct sum
function printDistinct(a, n)
{
    var maxSum = 0;
 
    // Find the sum of array elements
    for(var i = 0; i < n; i++)
    {
        maxSum += a[i];
    }
 
    // Function to print all the distinct sum
    subsetSum(a, n, maxSum);
}
 
// Driver Code
var arr = [ 2, 3, 4, 5, 6 ];
var n = arr.length;
 
printDistinct(arr, n);
 
// This code is contributed by importantly
 
</script>
Producción: 

0 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 20 21

 

Complejidad temporal O(suma*n) 
Espacio auxiliar: O(suma)
 

Publicación traducida automáticamente

Artículo escrito por Vishwanath Sharma y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *