#include <stdio.h>
#include <stdbool.h>
bool backtrack(int nums[], int n, int target, int index, int current_sum) {
if (current_sum == target) return true; // found exact sum
if (current_sum > target || index == n) return false; // overshoot or no more numbers
// choose current number
if (backtrack(nums, n, target, index + 1, current_sum + nums[index]))
return true;
// skip current number
if (backtrack(nums, n, target, index + 1, current_sum))
return true;
return false; // no solution found
}
bool greedy(int nums[], int n, int target) {
int sum = 0;
for (int i = n - 1; i >= 0; i--) {
if (nums[i] <= target - sum) {
sum += nums[i];
if (sum == target) return true;
}
}
return false;
}
int main() {
int nums[] = {3, 4, 5, 8};
int n = 4;
int target = 7;
if (greedy(nums, n, target))
printf("Greedy: Found a combination summing to %d\n", target);
else
printf("Greedy: No combination found for %d\n", target);
if (backtrack(nums, n, target, 0, 0))
printf("Backtracking: Found a combination summing to %d\n", target);
else
printf("Backtracking: No combination found for %d\n", target);
return 0;
}
if (current_sum == target) return true; // found exact sum
stop when exact sum is found
if (current_sum > target || index == n) return false; // overshoot or no more numbers
stop if sum too big or no more numbers
if (backtrack(nums, n, target, index + 1, current_sum + nums[index])) return true;
try including current number
if (backtrack(nums, n, target, index + 1, current_sum)) return true;
try excluding current number
for (int i = n - 1; i >= 0; i--) { if (nums[i] <= target - sum) { sum += nums[i]; if (sum == target) return true; } }
greedy picks largest numbers fitting in remaining sum
Greedy: No combination found for 7
Backtracking: Found a combination summing to 7