The Problem:
Suppose we have a set of integers, and we want to find all possible subsets of that set whose sum is equal to a given target number.
The Solution:
We can use backtracking to explore all possible subsets of the set and keep track of the ones that add up to the target sum.
The Java Program:
public class SubsetSumBacktracking {
public static void main(String[] args) {
int[] set = {3, 9, 8, 4, 5, 7};
int targetSum = 15;
findSubsets(set, targetSum);
}
public static void findSubsets(int[] set, int targetSum) {
boolean[] used = new boolean[set.length];
int sumSoFar = 0;
findSubsetsHelper(set, used, sumSoFar, targetSum, 0);
}
public static void findSubsetsHelper(int[] set, boolean[] used, int sumSoFar, int targetSum, int start) {
if (sumSoFar == targetSum) {
// We have found a subset that adds up to the target sum
printSubset(set, used);
} else if (sumSoFar < targetSum) {
// Try all possible combinations of unused elements
for (int i = start; i < set.length; i++) {
if (!used[i]) {
used[i] = true;
sumSoFar += set[i];
findSubsetsHelper(set, used, sumSoFar, targetSum, i + 1);
// Backtrack by undoing the last element added to the sum
used[i] = false;
sumSoFar -= set[i];
}
}
}
}
public static void printSubset(int[] set, boolean[] used) {
System.out.print("{ ");
for (int i = 0; i < set.length; i++) {
if (used[i]) {
System.out.print(set[i] + " ");
}
}
System.out.println("}");
}
}
Explanation:
- The main method initializes the set of integers and the target sum and calls the "findSubsets" method to start the backtracking process.
- The "findSubsets" method initializes a boolean array called "used" to keep track of which elements of the set have been used so far, and a variable called "sumSoFar" to keep track of the sum of the elements used in the current subset. It then calls the "findSubsetsHelper" method to start the recursive backtracking process.
- The "findSubsetsHelper" method is where the backtracking happens. If the "sumSoFar" equals the "targetSum", it means we have found a subset that adds up to the target sum, so we call the "printSubset" method to print out the subset.
- If the "sumSoFar" is less than the "targetSum", it means we still have room to add more elements to the subset. We loop through the remaining unused elements of the set and try adding each one to the sum by setting its corresponding value in the "used" array to "true". We then recursively call "findSubsetsHelper" with the updated "used" array, "sumSoFar", and "start" index (which is incremented by 1 to avoid using the same element twice).
- If the recursive call returns without finding a subset

No comments:
Post a Comment