Unique subsequences of length K with given sum | 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 ; Prlet resultant array ; End this recursion stack ; Check all the combinations using backtracking ; Check all the combinations using backtracking ; Given array ; To store the subsequence ; Function Call
function comb ( arr , len , r , ipos , op , opos , sum ) { if ( opos == r ) { let sum2 = 0 ; for ( let i = 0 ; i < opos ; i ++ ) { sum2 = sum2 + op [ i ] ; } if ( sum == sum2 ) { for ( let i = 0 ; i < opos ; i ++ ) document . write ( op [ i ] + " " ) ; document . write ( ) ; } 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 ) ; } } let arr = [ 4 , 6 , 8 , 2 , 12 ] ; let K = 3 ; let S = 20 ; let N = arr . length ; let op = Array . from ( { length : N } , ( _ , i ) => 0 ) ; comb ( arr , N , K , 0 , op , 0 , S ) ;