-
Notifications
You must be signed in to change notification settings - Fork 0
/
sub_of_subset.c
49 lines (46 loc) · 1.35 KB
/
sub_of_subset.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// AIM: TO IMPLEMENT SUM OF SUBSET PROBLEM IN C
#include <stdio.h>
#include <stdlib.h>
static int total_nodes;
void printValues(int A[], int size) {
for (int i = 0; i < size; i++) {
printf("%*d", 5, A[i]);
}
printf("\n");
}
void subset_sum(int s[], int t[], int s_size, int t_size, int sum, int ite, int const target_sum) {
total_nodes++;
if (target_sum == sum) {
printValues(t, t_size);
subset_sum(s, t, s_size, t_size - 1, sum - s[ite], ite + 1, target_sum);
return;
}
else {
for (int i = ite; i < s_size; i++) {
t[t_size] = s[i];
// printf("\n I am s[i] : %d", s[i]);
subset_sum(s, t, s_size, t_size + 1, sum + s[i], i + 1, target_sum);
}
}
}
void generateSubsets(int s[], int size, int target_sum) {
int* tuplet_vector = (int*)malloc(size * sizeof(int));
subset_sum(s, tuplet_vector, size, 0, 0, 0, target_sum);
free(tuplet_vector);
}
int main() {
int set[] = { 5, 10, 12, 13, 15, 18 };
int size = sizeof(set) / sizeof(set[0]);
int d = 30;
printf("The set is ");
printValues(set, size);
generateSubsets(set, size, d);
printf("Total Nodes generated %d\n", total_nodes);
return 0;
}
// OUTPUT:
// The set is 5 10 12 13 15 18
// 5 10 15
// 5 12 13
// 12 18
// Total Nodes generated 64