Number of ways to write N as a sum of K non | Java program for the above approach ; 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
import java . util . * ; class GFG { static int countWays ( int n , int m ) { int [ ] [ ] dp = new int [ m + 1 ] [ n + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) { dp [ 1 ] [ i ] = 1 ; if ( i != 0 ) { dp [ 1 ] [ i ] += dp [ 1 ] [ i - 1 ] ; } } for ( int i = 2 ; i <= m ; i ++ ) { for ( int j = 0 ; j <= n ; j ++ ) { if ( j == 0 ) { dp [ i ] [ j ] = dp [ i - 1 ] [ j ] ; } else { dp [ i ] [ j ] = dp [ i - 1 ] [ j ] ; if ( i == m && j == n ) { return dp [ i ] [ j ] ; } dp [ i ] [ j ] += dp [ i ] [ j - 1 ] ; } } } return Integer . MIN_VALUE ; } public static void main ( String [ ] args ) { int N = 2 , K = 3 ; System . out . print ( countWays ( N , K ) ) ; } }