UPDATE: I've updated the code again, I'm getting output that adds to the target sum. Still have 2 problems: it uses a value more times than it appears in the original and it doesn't print all unique solutions
Code:
#include <stdio.h>
#define MAX 1024
int coins_array[] = {1,1,1,1,1,3,3,3,3,3,3,3,3,3,3,10,10,10,10,10,15,15,15,15,15,15};
int N = sizeof(coins_array) / sizeof(coins_array[0]);
int S = 27, Sol[MAX], IndexUsed[MAX], total;
int acceptable(int step)
{
int i = 0, sum = 0;
for(i = 1; i <= step; i++)
{
sum += Sol[i];
}
if((sum <= S) && (step <= N))
return 1;
else
return 0;
}
int solution(int sum)
{
if (sum == S)
return 1;
return 0;
}
void print_solution(int step)
{
int i;
for(i = 1 ; i <= step ; ++i)
//printf("%d (%d) ",Sol[i], IndexUsed[i]);
printf("%d ", Sol[i]);
printf("\n");
}
void back(int step)
{
int i;
for(i = IndexUsed[step]+1; i < N; i++)
{
Sol[step] = coins_array[i];
IndexUsed[step] = i;
total += coins_array[i];
if(acceptable(step) == 1)
{
if(solution(total) == 1)
{
print_solution(step);
}
else
back(step+1);
}
total -= coins_array[i];
}
}
int main()
{
back(1);
return 0;
}
Output:
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 10
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 10
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 10
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 10
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 10
1 1 1 1 1 1 1 1 1 1 1 1 15
1 1 1 1 1 1 1 1 1 1 1 1 15
1 1 1 1 1 1 1 1 1 1 1 1 15
1 1 1 1 1 1 1 1 1 1 1 1 15
1 1 1 1 1 1 1 1 1 1 1 1 15
1 1 1 1 1 1 1 1 1 1 1 1 15