Number of ways to write N as a sum of K non | Function to count the number of ways to write N as sum of k non - negative integers ; Initialise dp [ ] [ ] array ; Only 1 way to choose the value with sum K ; Initialise sum ; Count the ways from previous states ; Update the sum ; Return the final count of ways ; Driver Code ; Function call
function countWays ( n , m ) { var dp = Array . from ( Array ( m + 1 ) , ( ) => Array ( n + 1 ) ) ; for ( var i = 0 ; i <= n ; i ++ ) { dp [ 1 ] [ i ] = 1 ; } var sum ; for ( var i = 2 ; i <= m ; i ++ ) { for ( var j = 0 ; j <= n ; j ++ ) { sum = 0 ; for ( var k = 0 ; k <= j ; k ++ ) { sum += dp [ i - 1 ] [ k ] ; } dp [ i ] [ j ] = sum ; } } return dp [ m ] [ n ] ; } var N = 2 , K = 3 ; document . write ( countWays ( N , K ) ) ;