Ways to sum to N using array elements with repetition allowed

Given a set of m distinct positive integers and a value ‘N’. The problem is to count the total number of ways we can form ‘N’ by doing sum of the array elements. Repetitions and different arrangements are allowed.

Examples :

Input : arr = {1, 5, 6}, N = 7
Output : 6

Explanation:- The different ways are:
1+1+1+1+1+1+1
1+1+5
1+5+1
5+1+1
1+6
6+1

Input : arr = {12, 3, 1, 9}, N = 14
Output : 150

Approach: The approach is based on the concept of dynamic programming.

countWays(arr, m, N)
        Declare and initialize count[N + 1] = {0}
        count[0] = 1
        for i = 1 to N
            for j = 0 to m - 1
                if i >= arr[j]
                   count[i] += count[i - arr[j]]
        return count[N] 

Below is the implementation of above approach.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

chevron_right


Output:

Total number of ways = 6

Time Complexity: O(N*m)

This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up

Improved By : nitin mittal, AnkitRai01