All unique combinations whose sum equals to K (Combination Sum II)
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 combination is equal to K.
Examples:
Input: arr[] = {1, 2, 3}, K = 3
Output:
{1, 2}
{3}
Explanation:
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++
#include <bits/stdc++.h>
using namespace std;
void unique_combination( int l, int sum, int K,
vector< int >& local,
vector< int >& A)
{
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 ( int i = l; i < A.size(); i++)
{
if (sum + A[i] > K)
continue ;
if (i > l and A[i] == A[i - 1])
continue ;
local.push_back(A[i]);
unique_combination(i + 1, sum + A[i], K, local, A);
local.pop_back();
}
}
void Combination(vector< int > A, int K)
{
sort(A.begin(), A.end());
vector< int > local;
unique_combination(0, 0, K, local, A);
}
int main()
{
vector< int > A = { 10, 1, 2, 7, 6, 1, 5 };
int K = 8;
Combination(A, K);
return 0;
}
|
Java
import java.util.*;
class GFG {
static void unique_combination( int l, int sum, int K,
Vector<Integer> local,
Vector<Integer> A)
{
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 ( int i = l; i < A.size(); i++) {
if (sum + A.get(i) > K)
continue ;
if (i > l && A.get(i) == A.get(i - 1 ) )
continue ;
local.add(A.get(i));
unique_combination(i + 1 , sum + A.get(i), K,
local, A);
local.remove(local.size() - 1 );
}
}
static void Combination(Vector<Integer> A, int K)
{
Collections.sort(A);
Vector<Integer> local = new Vector<Integer>();
unique_combination( 0 , 0 , K, local, A);
}
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 ;
Combination(A, K);
}
}
|
Python3
def unique_combination(l, sum , K, local, A):
if ( sum = = K):
print ( "{" , end = "")
for i in range ( len (local)):
if (i ! = 0 ):
print ( " " , end = "")
print (local[i], end = "")
if (i ! = len (local) - 1 ):
print ( ", " , end = "")
print ( "}" )
return
for i in range (l, len (A), 1 ):
if ( sum + A[i] > K):
continue
if (i > l and
A[i] = = A[i - 1 ]):
continue
local.append(A[i])
unique_combination(i + 1 , sum + A[i],
K, local, A)
local.remove(local[ len (local) - 1 ])
def Combination(A, K):
A.sort(reverse = False )
local = []
unique_combination( 0 , 0 , K, local, A)
if __name__ = = '__main__' :
A = [ 10 , 1 , 2 , 7 , 6 , 1 , 5 ]
K = 8
Combination(A, K)
|
C#
using System;
using System.Collections.Generic;
class GFG {
static void unique_combination( int l, int sum, int K,
List< int > local,
List< int > A)
{
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 ( int i = l; i < A.Count; i++)
{
if (sum + A[i] > K)
continue ;
if (i >l && A[i] == A[i - 1])
continue ;
local.Add(A[i]);
unique_combination(i + 1, sum + A[i], K, local,
A);
local.RemoveAt(local.Count - 1);
}
}
static void Combination(List< int > A, int K)
{
A.Sort();
List< int > local = new List< int >();
unique_combination(0, 0, K, local, A);
}
public static void Main(String[] args)
{
int [] arr = { 10, 1, 2, 7, 6, 1, 5 };
List< int > A = new List< int >(arr);
int K = 8;
Combination(A, K);
}
}
|
Javascript
<script>
function unique_combination(l, sum, K, local, A) {
if (sum == K) {
document.write( "{" );
for (let i = 0; i < local.length; i++) {
if (i != 0)
document.write( " " );
document.write(local[i]);
if (i != local.length - 1)
document.write( ", " );
}
document.write( "}" + "<br>" );
return ;
}
for (let i = l; i < A.length; i++) {
if (sum + A[i] > K)
continue ;
if (i > l && A[i] == A[i - 1])
continue ;
local.push(A[i]);
unique_combination(i + 1, sum + A[i], K, local, A);
local.pop();
}
}
function Combination(A, K) {
A.sort((a, b) => a - b);
let local = [];
unique_combination(0, 0, K, local, A);
}
let A = [10, 1, 2, 7, 6, 1, 5];
let K = 8;
Combination(A, K);
</script>
|
Output
{1, 1, 6}
{1, 2, 5}
{1, 7}
{2, 6}
Time Complexity: O(n log n) for sorting, O(2^n) for generating a number of combinations. If ‘k’ is the avg length of every combination then adding it to the resultant list would take O(k x 2^n). Total complexity is O(n log n)+O(k x 2^n)
Auxiliary Space: If ‘k’ is the avg length of every combination and ‘t’ is the no. of combinations then space complexity would be O(k x t)
Last Updated :
11 Sep, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...