All unique combinations whose sum equals to K | 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
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 ( " " + " " ) ; 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 ) ;