Ways to sum to N using array elements with repetition allowed | C ++ implementation to count ways to sum up to a given value N ; function to count the total number of ways to sum up to ' N ' ; base case ; count ways for all values up to ' N ' and store the result ; if i >= arr [ j ] then accumulate count for value ' i ' as ways to form value ' i - arr [ j ] ' ; required number of ways ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countWays ( int arr [ ] , int m , int N ) { int count [ N + 1 ] ; memset ( count , 0 , sizeof ( count ) ) ; count [ 0 ] = 1 ; for ( int i = 1 ; i <= N ; i ++ ) for ( int j = 0 ; j < m ; j ++ ) if ( i >= arr [ j ] ) count [ i ] += count [ i - arr [ j ] ] ; return count [ N ] ; } int main ( ) { int arr [ ] = { 1 , 5 , 6 } ; int m = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int N = 7 ; cout << " Total ▁ number ▁ of ▁ ways ▁ = ▁ " << countWays ( arr , m , N ) ; return 0 ; }