Given an array of distinct positive integers, find the total number of distinct permutations that add up to a given target, where each array element may be used any number of times.

For example,

Input: nums = [1, 2, 3, 4], target = 3
Output: 4
Explanation: The permutations of [1, 2, 3, 4] with sum 3 are:
[1, 1, 1]
[1, 2]
[2, 1]
[3]
 
Input: nums = [1, 3, 5], target = 5
Output: 5
Explanation: The permutations of [1, 3, 5] with sum 5 are:
[1, 1, 1, 1, 1]
[1, 1, 3]
[1, 3, 1]
[3, 1, 1]
[5]

We can use recursion to solve this problem. The idea is to consider each element in the array, and recur to see if the target can be reached by choosing the current number. If choosing a number results in the solution, we increment the total number of permutations found so far. Following is the C++, Java, and Python implementation based on the idea:

C++


Download  Run Code

Output:

4

Java


Download  Run Code

Output:

4

Python


Download  Run Code

Output:

4

Since each recursive call is making n recursive calls, the time complexity of the above solution is exponential and it requires extra space for the call stack.

 
When the recursion tree is drawn for higher values of the target, we can see that the problem can be divided into smaller subproblems that are repeated. In other words, we will ultimately end up computing the same subproblem several times. Dynamic programming can be used to solve problems with optimal substructure and overlapping subproblems, where the subproblem solutions are memoized rather than repeatedly computed.

C++


Download  Run Code

Output:

4

Java


Download  Run Code

Output:

4

Python


Download  Run Code

Output:

4

The time complexity of the above memoized solution is O(n.target), where n is the size of the array. The auxiliary space used by the program is O(target).

 
Even better, we can write a bottom-up variant of the above memoized version. By starting with smaller subproblems and working our way up, we can solve larger subproblems. The bottom-up method calculates T[i] using the smaller values of i that have already been computed.

C++


Download  Run Code

Output:

4

Java


Download  Run Code

Output:

4

Python


Download  Run Code

Output:

4