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
def countWays ( n , m ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( n + 1 ) ] for i in range ( m + 1 ) ] NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT dp [ 1 ] [ i ] = 1 NEW_LINE DEDENT sum = 0 NEW_LINE for i in range ( 2 , m + 1 ) : NEW_LINE INDENT for j in range ( n + 1 ) : NEW_LINE INDENT sum = 0 NEW_LINE for k in range ( j + 1 ) : NEW_LINE INDENT sum += dp [ i - 1 ] [ k ] NEW_LINE DEDENT dp [ i ] [ j ] = sum NEW_LINE DEDENT DEDENT return dp [ m ] [ n ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 2 NEW_LINE K = 3 NEW_LINE print ( countWays ( N , K ) ) NEW_LINE DEDENT