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 ; Fill the dp [ ] [ ] with sum = m ; Iterate the dp [ ] [ ] to fill the dp [ ] [ ] array ; Condition for first column ; Else fill the dp [ ] [ ] with sum till ( i , j ) ; If reach the end , then return the value ; Update at current index ; Driver Code ; Function call
def countWays ( n , m ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( n + 1 ) ] for j in range ( m + 1 ) ] NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT dp [ 1 ] [ i ] = 1 NEW_LINE if ( i != 0 ) : NEW_LINE INDENT dp [ 1 ] [ i ] += dp [ 1 ] [ i - 1 ] NEW_LINE DEDENT DEDENT for i in range ( 2 , m + 1 ) : NEW_LINE INDENT for j in range ( n + 1 ) : NEW_LINE INDENT if ( j == 0 ) : NEW_LINE INDENT dp [ i ] [ j ] = dp [ i - 1 ] [ j ] NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = dp [ i - 1 ] [ j ] NEW_LINE if ( i == m and j == n ) : NEW_LINE INDENT return dp [ i ] [ j ] NEW_LINE DEDENT dp [ i ] [ j ] += dp [ i ] [ j - 1 ] NEW_LINE DEDENT DEDENT DEDENT DEDENT N = 2 NEW_LINE K = 3 NEW_LINE print ( countWays ( N , K ) ) NEW_LINE