Perfect Sum Problem

Configurare noua (How To)

Situatie

Given an array arr[] of integers and an integer K, the task is to print all subsets of the given array with the sum equal to the given target K.

Solutie

Examples:

Input: arr[] = {5, 10, 12, 13, 15, 18}, K = 30
Output: {12, 18}, {5, 12, 13}, {5, 10, 15}
Explanation: 
Subsets with sum 30 are:
12 + 18 = 30
5 + 12 + 13 = 30
5 + 10 + 15 = 30

Input: arr[] = {1, 2, 3, 4}, K = 5
Output: {2, 3}, {1, 4}

Approach: The idea is to find out all the subsets using the Power Set concept. For every set, check if the sum of the set is equal to K or not. If it is equal, then the set is printed.

Below is the implementation of the above approach:

// C# implementation of the above approach
using System;

class GFG
{

// Function to print the subsets whose
// sum is equal to the given target K
public static void sumSubsets(
int []set, int n, int target)
{
// Create the new array with size
// equal to array set[] to create
// binary array as per n(decimal number)
int []x = new int[set.Length];
int j = set.Length – 1;

// Convert the array into binary array
while (n > 0)
{
x[j] = n % 2;
n = n / 2;
j–;
}

int sum = 0;

// Calculate the sum of this subset
for (int i = 0; i < set.Length; i++)
if (x[i] == 1)
sum = sum + set[i];

// Check whether sum is equal to target
// if it is equal, then print the subset
if (sum == target)
{
Console.Write(“{“);
for (int i = 0; i < set.Length; i++)
if (x[i] == 1)
Console.Write(set[i] + “, “);
Console.Write(“}, “);
}
}

// Function to find the subsets with sum K
public static void findSubsets(int[] arr, int K)
{
// Calculate the total no. of subsets
int x = (int)Math.Pow(2, arr.Length);

// Run loop till total no. of subsets
// and call the function for each subset
for (int i = 1; i < x; i++)
sumSubsets(arr, i, K);
}

// Driver code
public static void Main(String []args)
{
int []arr = { 5, 10, 12, 13, 15, 18 };
int K = 30;

findSubsets(arr, K);
}
}

Output:

{12, 18, }, {5, 12, 13, }, {5, 10, 15, },

Tip solutie

Permanent

Voteaza

(3 din 9 persoane apreciaza acest articol)

Despre Autor

Leave A Comment?