All unique combinations whose sum equals to K

Given an array arr[] of size N and an integer K. The task is to find all the unique combinations from the given array such that sum of the elements in each combiantion is equal to K.

Examples:

Input: arr[] = {1, 2, 3}, K = 3
Output:
{1, 2}
{3}
These are the combinations whose sum equals to 3.

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

Approach: Some elements can be repeated in the given array. Make sure to iterate over the number of occurrences of those elements to avoid repeated combinations. Once you do that, things are fairly straightforward. Call a recursive function with the remaining sum and make the indices to move forward. When the sum reaches K, print all the elements which were selected to get this sum.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to find all unique combination of
// given elements such that their sum is K
void unique_combination(int l, int sum, int K,
                        vector<int>& local, vector<int>& A)
{
    // If a unique combination is found
    if (sum == K) {
        cout << "{";
        for (int i = 0; i < local.size(); i++) {
            if (i != 0)
                cout << " ";
            cout << local[i];
            if (i != local.size() - 1)
                cout << ", ";
        }
        cout << "}" << endl;
        return;
    }
  
    // For all other combinations
    for (int i = l; i < A.size(); i++) {
  
        // Check if the sum exceeds K
        if (sum + A[i] > K)
            continue;
  
        // Check if it is repeated or not
        if (i and A[i] == A[i - 1] and i > l)
            continue;
  
        // Take the element into the combination
        local.push_back(A[i]);
  
        // Recursive call
        unique_combination(i + 1, sum + A[i],
                           K, local, A);
  
        // Remove element from the combination
        local.pop_back();
    }
}
  
// Function to find all combination
// of the given elements
void Combination(vector<int> A, int K)
{
    // Sort the given elements
    sort(A.begin(), A.end());
  
    // To store combination
    vector<int> local;
  
    unique_combination(0, 0, K, local, A);
}
  
// Driver code
int main()
{
    vector<int> A = { 10, 1, 2, 7, 6, 1, 5 };
  
    int K = 8;
  
    // Function call
    Combination(A, K);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of the approach
import java.util.*;
  
class GFG 
{
  
// Function to find all unique combination of
// given elements such that their sum is K
static void unique_combination(int l, int sum, int K, 
                               Vector<Integer> local, 
                               Vector<Integer> A)
{
    // If a unique combination is found
    if (sum == K) 
    {
        System.out.print("{");
        for (int i = 0; i < local.size(); i++)
        {
            if (i != 0)
                System.out.print(" ");
            System.out.print(local.get(i));
            if (i != local.size() - 1)
                System.out.print(", ");
        }
        System.out.println("}");
        return;
    }
  
    // For all other combinations
    for (int i = l; i < A.size(); i++)
    {
  
        // Check if the sum exceeds K
        if (sum + A.get(i) > K)
            continue;
  
        // Check if it is repeated or not
        if (i == 1 &&
            A.get(i) == A.get(i - 1) && 
            i > l)
            continue;
  
        // Take the element into the combination
        local.add(A.get(i));
  
        // Recursive call
        unique_combination(i + 1, sum + A.get(i),
                           K, local, A);
  
        // Remove element from the combination
        local.remove(local.size() - 1);
    }
}
  
// Function to find all combination
// of the given elements
static void Combination(Vector<Integer> A, int K)
{
    // Sort the given elements
    Collections.sort(A);
  
    // To store combination
    Vector<Integer> local = new Vector<Integer>();
  
    unique_combination(0, 0, K, local, A);
}
  
// Driver code
public static void main(String[] args) 
{
    Integer []arr = { 10, 1, 2, 7, 6, 1, 5 };
    Vector<Integer> A = new Vector<>(Arrays.asList(arr));
  
    int K = 8;
  
    // Function call
    Combination(A, K);
}
}
  
// This code is contributed by PrinciRaj1992 

chevron_right


C#

// C# implementation of the approach
using System;
using System.Collections.Generic;

class GFG
{

// Function to find all unique combination of
// given elements such that their sum is K
static void unique_combination(int l, int sum, int K,
List local,
List A)
{
// If a unique combination is found
if (sum == K)
{
Console.Write(“{“);
for (int i = 0; i < local.Count; i++) { if (i != 0) Console.Write(" "); Console.Write(local[i]); if (i != local.Count - 1) Console.Write(", "); } Console.WriteLine("}"); return; } // For all other combinations for (int i = l; i < A.Count; i++) { // Check if the sum exceeds K if (sum + A[i] > K)
continue;

// Check if it is repeated or not
if (i == 1 &&
A[i] == A[i – 1] &&
i > l)
continue;

// Take the element into the combination
local.Add(A[i]);

// Recursive call
unique_combination(i + 1, sum + A[i],
K, local, A);

// Remove element from the combination
local.RemoveAt(local.Count – 1);
}
}

// Function to find all combination
// of the given elements
static void Combination(List A, int K)
{
// Sort the given elements
A.Sort();

// To store combination
List local = new List();

unique_combination(0, 0, K, local, A);
}

// Driver code
public static void Main(String[] args)
{
int []arr = { 10, 1, 2, 7, 6, 1, 5 };
List A = new List(arr);

int K = 8;

// Function call
Combination(A, K);
}
}

// This code is contributed by Rajput-Ji

Output:

{1,  1,  6}
{1,  2,  5}
{1,  7}
{2,  6}


My Personal Notes arrow_drop_up

pawanasipugmailcom

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : princiraj1992, Rajput-Ji



Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.