#include <stdio.h>
#include <stdlib.h>
// Node for storing one combination
typedef struct Node {
int *combination;
int size;
struct Node *next;
} Node;
// Append new combination to result list
void append(Node **head, int *comb, int size) {
Node *new_node = (Node*)malloc(sizeof(Node));
new_node->combination = (int*)malloc(size * sizeof(int));
for (int i = 0; i < size; i++) {
new_node->combination[i] = comb[i];
}
new_node->size = size;
new_node->next = NULL;
if (*head == NULL) {
*head = new_node;
} else {
Node *temp = *head;
while (temp->next != NULL) temp = temp->next;
temp->next = new_node;
}
}
// Recursive helper to find combinations
void backtrack(int *candidates, int candidatesSize, int target, int start, int *comb, int combSize, Node **result) {
if (target == 0) {
append(result, comb, combSize); // save valid combination
return;
}
for (int i = start; i < candidatesSize; i++) {
if (candidates[i] > target) continue; // skip if candidate too big
comb[combSize] = candidates[i];
backtrack(candidates, candidatesSize, target - candidates[i], i, comb, combSize + 1, result); // reuse i
}
}
// Print all combinations
void printResult(Node *head) {
Node *curr = head;
while (curr != NULL) {
for (int i = 0; i < curr->size; i++) {
printf("%d", curr->combination[i]);
if (i < curr->size - 1) printf(" -> ");
}
printf(" -> null\n");
curr = curr->next;
}
}
int main() {
int candidates[] = {2, 3, 6, 7};
int target = 7;
int candidatesSize = sizeof(candidates) / sizeof(candidates[0]);
int *comb = (int*)malloc(target * sizeof(int));
Node *result = NULL;
backtrack(candidates, candidatesSize, target, 0, comb, 0, &result);
printResult(result);
free(comb);
// Free result list omitted for brevity
return 0;
}if (target == 0) { append(result, comb, combSize); return; }
save combination when sum matches target
for (int i = start; i < candidatesSize; i++) { if (candidates[i] > target) continue;
skip candidates larger than remaining target
comb[combSize] = candidates[i]; backtrack(candidates, candidatesSize, target - candidates[i], i, comb, combSize + 1, result);
choose candidate and recurse with reduced target, allowing reuse
2 -> 2 -> 3 -> null
7 -> null