Print all non | Utility function to print array arr [ 0. . n - 1 ] ; Recursive Function to generate all non - increasing sequences with sum x arr [ ] -- > Elements of current sequence curr_sum -- > Current Sum curr_idx -- > Current index in arr [ ] ; If current sum is equal to x , then we found a sequence ; Try placing all numbers from 1 to x - curr_sum at current index ; The placed number must also be smaller than previously placed numbers and it may be equal to the previous stored value , i . e . , arr [ curr_idx - 1 ] if there exists a previous number ; Place number at curr_idx ; Recur ; Try next number ; A wrapper over generateUtil ( ) ; Array to store sequences on by one ; Driver code
function printArr ( arr , n ) { for ( let i = 0 ; i < n ; i ++ ) document . write ( arr [ i ] + " " ) ; document . write ( " " ) ; } function generateUtil ( x , arr , curr_sum , curr_idx ) { if ( curr_sum == x ) { printArr ( arr , curr_idx ) ; return ; } let num = 1 ; while ( num <= x - curr_sum && ( curr_idx == 0 num <= arr [ curr_idx - 1 ] ) ) { arr [ curr_idx ] = num ; generateUtil ( x , arr , curr_sum + num , curr_idx + 1 ) ; num ++ ; } } function generate ( x ) { let arr = new Array ( x ) ; generateUtil ( x , arr , 0 , 0 ) ; } let x = 5 ; generate ( x ) ;