Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save outlinepix/cdecefa438bc0c2e36abac4e4c3d8688 to your computer and use it in GitHub Desktop.
Save outlinepix/cdecefa438bc0c2e36abac4e4c3d8688 to your computer and use it in GitHub Desktop.
Counting Coin Change Sum problem using Recursion and Momoization in C language
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
int *cache(int n);
int canSum(int target, int numbers[], int len, int *memo);
int main(int argc, char const *argv[])
{
assert(canSum(11, (int[]){1, 4}, 2, cache(11)));
printf("Test 1: Passed\n");
assert(canSum(17, (int[]){3, 4, 5, 6}, 4, cache(17)));
printf("Test 2: Passed\n");
assert(canSum(70, (int[]){7, 14}, 2, cache(100)));
printf("Test 3: Passed\n");
return 0;
}
int canSum(int target, int numbers[], int len, int *memo)
{
if (memo[target] == target)
{
return memo[target];
}
int remainder = -1;
if (target == 0)
{
return true;
}
if (target < 0)
{
return false;
}
for (int i = 0; i < len; i++)
{
/**
* *This is for debugging purpose.
*/
// printf("Try [%d]:[%d - %d] = %d \n", i, target, numbers[i], target - numbers[i]);
remainder = target - numbers[i];
if (remainder == 0)
{
return true;
}
if (canSum(remainder, numbers, len, memo) == true)
{
memo[target] = true;
return memo[target];
}
}
memo[target] = false;
return memo[target];
}
int *cache(int n)
{
int *cache = (int *)malloc(sizeof(int) * n);
for (int i = 0; i < n; i++)
{
cache[i] = -1;
}
return cache;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment