Ways to sum to N using array elements with repetition allowed in C++


In this problem, we are given an array of integers and a number N. Our task is to count the total number of ways N can be generated by adding elements of the array. All combinations and repetitions are allowed.

Let’s take an example to understand the problem,

Input

arr = {1, 3, 5} N = 6

Output

8

Explanation

The ways are −

5+1, 1+5, 3+3, 3+1+1+1, 1+3+1+1, 1+1+3+1, 1+1+1+3, 1+1+1+1+1+1

To solve this problem, we need to use a different approach as all types of combinations will be treated differently so, if the number is a sum of 4 elements of array 4 different ways are considered(as shown in example). For solve such a problem, we need to use dynamic programming approach and the below program will show the implementation.

Example

 Live Demo

#include <iostream>
#include <cstring>
using namespace std;
int arraySumWays(int array[], int size, 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 < size; j++)
         if (i >= array[j])
            count[i] += count[i - array[j]];
   return count[N];
}
int main() {
   int array[] = {1, 5, 6};
   int size = sizeof(array) / sizeof(array[0]);
   int N = 7;
   cout<<"Total number of ways inwhich "<<N<<" can be generated using sum of elements of array is "      <<arraySumWays(array, size, N);
   return 0;
}

Output

Total number of ways inwhich 7 can be generated using sum of elements of array is 6

Updated on: 17-Jul-2020

462 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements