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 ; 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
def comb ( arr , Len , r , ipos , op , opos , Sum ) : NEW_LINE INDENT if ( opos == r ) : NEW_LINE INDENT sum2 = 0 NEW_LINE for i in range ( opos ) : NEW_LINE INDENT sum2 = sum2 + op [ i ] NEW_LINE DEDENT if ( Sum == sum2 ) : NEW_LINE INDENT for i in range ( opos ) : NEW_LINE INDENT print ( op [ i ] , end = " , ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT return NEW_LINE DEDENT if ( ipos < Len ) : NEW_LINE INDENT comb ( arr , Len , r , ipos + 1 , op , opos , Sum ) NEW_LINE op [ opos ] = arr [ ipos ] NEW_LINE comb ( arr , Len , r , ipos + 1 , op , opos + 1 , Sum ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 6 , 8 , 2 , 12 ] NEW_LINE K = 3 NEW_LINE S = 20 NEW_LINE N = len ( arr ) NEW_LINE op = [ 0 ] * N NEW_LINE comb ( arr , N , K , 0 , op , 0 , S ) NEW_LINE DEDENT