All unique combinations whose sum equals to K | C ++ implementation of the approach ; Function to find all unique combination of given elements such that their sum is K ; If a unique combination is found ; For all other combinations ; Check if the sum exceeds K ; Check if it is repeated or not ; Take the element into the combination ; Recursive call ; Remove element from the combination ; Function to find all combination of the given elements ; Sort the given elements ; To store combination ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE 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 ; }