Print combinations of distinct numbers which add up to give sum N | arr [ ] to store all the distinct elements index - next location in array num - given number reducedNum - reduced number ; Set to store all the distinct elements ; Base condition ; Iterate over all the elements and store it into the set ; Calculate the sum of all the elements of the set ; Compare whether the sum is equal to n or not , if it is equal to n print the numbers ; Find previous number stored in the array ; Store all the numbers recursively into the arr [ ] ; Function to find all the distinct combinations of n ; Driver code
def findCombinationsUtil ( arr , index , n , red_num ) : NEW_LINE INDENT s = set ( ) NEW_LINE sum = 0 NEW_LINE if ( red_num < 0 ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( red_num == 0 ) : NEW_LINE INDENT for i in range ( index ) : NEW_LINE INDENT s . add ( arr [ i ] ) NEW_LINE DEDENT for itr in s : NEW_LINE INDENT sum = sum + ( itr ) NEW_LINE DEDENT if ( sum == n ) : NEW_LINE INDENT for i in s : NEW_LINE INDENT print ( i , end = " ▁ " ) NEW_LINE DEDENT print ( " " , ▁ end ▁ = ▁ " " ) NEW_LINE return NEW_LINE DEDENT DEDENT if ( index == 0 ) : NEW_LINE INDENT prev = 1 NEW_LINE DEDENT else : NEW_LINE INDENT prev = arr [ index - 1 ] NEW_LINE DEDENT for k in range ( prev , n + 1 , 1 ) : NEW_LINE INDENT arr [ index ] = k NEW_LINE findCombinationsUtil ( arr , index + 1 , n , red_num - k ) NEW_LINE DEDENT DEDENT def findCombinations ( n ) : NEW_LINE INDENT a = [ 0 for i in range ( n + 1 ) ] NEW_LINE findCombinationsUtil ( a , 0 , n , n ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 7 NEW_LINE findCombinations ( n ) NEW_LINE DEDENT