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:

    int ans=0;
int num;
for(int i=0; i<nums.size(); i++) {
num=nums[i];
ans+=dp(val-num);
}

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

int combinationSum4(vector<int>& nums, int target) {
nsum=0;
this->target=target;
this->nums=nums;
memo=vector<int>(target+1, -1);
return dp(target);

return nsum;
}

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

if(val==0) return 1;
if(val<0) return 0;

The remaining code is just typical dealings with the memo

Full code below

    int nsum;
vector<int> nums;
int target;

vector<int> memo;

int dp(int val) {
if(val==0) return 1;
if(val<0) return 0;
if(memo[val]!=-1) return memo[val];

int ans=0;
int num;
for(int i=0; i<nums.size(); i++) {
num=nums[i];
ans+=dp(val-num);
}
memo[val]=ans;
return memo[val];
}

int combinationSum4(vector<int>& nums, int target) {
nsum=0;
this->target=target;
this->nums=nums;
memo=vector<int>(target+1, -1);
int startsum=0;
return dp(target);

return nsum;
}

Comments

Popular posts from this blog

Wednesday, September 20th

Monday, September 11th

Tuesday, September 19th