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
function findCombinationsUtil ( arr , index , n , red_num ) { var s = new Set ( ) ; var sum = 0 ; if ( red_num < 0 ) { return ; } if ( red_num === 0 ) { for ( var i = 0 ; i < index ; i ++ ) { s . add ( arr [ i ] ) ; } for ( const itr of s ) { sum = sum + itr ; } if ( sum === n ) { for ( const i of s ) { document . write ( i + " " ) ; } document . write ( " " ) ; return ; } } var prev = index === 0 ? 1 : arr [ index - 1 ] ; for ( var k = prev ; k <= n ; k ++ ) { if ( index < n ) { arr [ index ] = k ; findCombinationsUtil ( arr , index + 1 , n , red_num - k ) ; } } } function findCombinations ( n ) { var a = new Array ( n ) . fill ( 0 ) ; findCombinationsUtil ( a , 0 , n , n ) ; } var n = 7 ; findCombinations ( n ) ;