Unique subsequences of length K with given sum | Java program for the above approach ; Function to find all the subsequences of a given length and having sum S ; Termination condition ; Add value to sum ; Check if the resultant sum equals to target sum ; If true ; Print resultant array ; End this recursion stack ; Check all the combinations using backtracking ; Check all the combinations using backtracking ; Driver Code ; Given array ; To store the subsequence ; Function Call
import java . util . * ; class GFG { static void comb ( int [ ] arr , int len , int r , int ipos , int [ ] op , int opos , int sum ) { if ( opos == r ) { int sum2 = 0 ; for ( int i = 0 ; i < opos ; i ++ ) { sum2 = sum2 + op [ i ] ; } if ( sum == sum2 ) { for ( int i = 0 ; i < opos ; i ++ ) System . out . print ( op [ i ] + " , ▁ " ) ; System . out . println ( ) ; } return ; } if ( ipos < len ) { comb ( arr , len , r , ipos + 1 , op , opos , sum ) ; op [ opos ] = arr [ ipos ] ; comb ( arr , len , r , ipos + 1 , op , opos + 1 , sum ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 4 , 6 , 8 , 2 , 12 } ; int K = 3 ; int S = 20 ; int N = arr . length ; int op [ ] = new int [ N ] ; comb ( arr , N , K , 0 , op , 0 , S ) ; } }