text: Number of ways to write N as a sum of K non | C ++ 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
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; int countWays ( int n , int m ) { int dp [ 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 ] ; } } } } int main ( ) { int N = 2 , K = 3 ; cout << countWays ( N , K ) ; return 0 ; }