Ways to sum to N using array elements with repetition allowed | Java implementation to count ways to sum up to a given value N ; method 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
class Gfg { static int arr [ ] = { 1 , 5 , 6 } ; static int countWays ( int N ) { int count [ ] = new int [ N + 1 ] ; count [ 0 ] = 1 ; for ( int i = 1 ; i <= N ; i ++ ) for ( int j = 0 ; j < arr . length ; j ++ ) if ( i >= arr [ j ] ) count [ i ] += count [ i - arr [ j ] ] ; return count [ N ] ; } public static void main ( String [ ] args ) { int N = 7 ; System . out . println ( " Total ▁ number ▁ of ▁ ways ▁ = ▁ " + countWays ( N ) ) ; } }