All unique combinations whose sum equals to K | Java 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
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 ) ; } }