Saturday, September 9th
Combination Sums
Given an array of integers and a target value, return the number of combinations that can add up to the target
I first approached the problem using brute force, but then with a timeout on values of {1, 2, 3} and a target of 40, pivoted to dynamic programming
This idea behind the dynamic programming approach here is like the earlier DP problem of moving right and down along a grid towards a finish square. In that type of problem, the total number of ways to reach a square equals the number of ways to reach the square above, plus the number of ways to reach the square to the left.
In this case, the number of ways to reach a target value equals the number of ways to reach a target value minus the values in nums. This forms the meat of the program, the recurrence relation in a top down approach:
The rest of the code is pretty boilerplate
We set a global value nsum to count the combinations. We set target and nums to global variables to make function calls easier to follow, and we declare a 1 dimensional memo array to store intermediate values
In the dp() function, we set the base case when the input value is 0, there is only 1 way to make that value and that's by no values. Any value less than 0 can't be made
The remaining code is just typical dealings with the memo
Full code below
Comments
Post a Comment