14. Perfect Sum Problem
The problem can be found at the following link: Question Link
My Approach
I have solved the Perfect Sum Problem using recursion with memoization. Here's how my approach works:
We define a recursive function
solve
that takes in the current indexi
, the remaining sumsum
, and a memoization tabledp
. This function calculates the number of ways to obtain the givensum
using elements from the arrayarr
starting from indexi
.Base case:
If
sum
becomes 0, we have found a valid combination, so we return 1 to count it.If we have reached the end of the array
arr
(i >= n), or ifsum
becomes negative, we return0
as there are no more elements to consider or the sum cannot be achieved.We check if the result for the current state (i, sum) is already calculated and stored in the
dp
array. If so, we return the cached result to avoid redundant calculations.
We initialize two variables
t
andnt
to count the number of ways by taking and not-taking the current elementarr[i]
, respectively.If the current element
arr[i]
is less than or equal tosum
, we can include it in the sum. So, we recursively call thesolve
function for the next indexi + 1
and the reduced sumsum - arr[i]
, and add this count tot
.We also recursively call the
solve
function for the next indexi + 1
and the same sumsum
, and add this count tont
.Finally, we update the
dp
array with the total count for the current state (i, sum) as(t + nt) % mod
, wheremod
is a constant defined as 1e9 + 7. We return this count.
Time and Auxiliary Space Complexity
Time Complexity: The time complexity of this solution is
O(n * sum)
, wheren
is the number of elements in thearr
array, andsum
is the target sum. This is because we have a recursive function with two parameters, and we memoize the results, so each state is calculated only once.Auxiliary Space Complexity: The auxiliary space complexity is
O(n * sum)
as well, due to the memoization tabledp
, which stores the results for all possible combinations of indices and sums.
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star
to the getlost01/gfg-potd repository.
Last updated