Wednesday, March 15, 2023

Tracking back with backtracking algorithm

Backtracking is a technique used in programming to explore all possible solutions to a problem by traversing a tree-like structure of possible outcomes. Here is an example of a Java program that uses backtracking to solve a simple problem.

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:

  1. The main method initializes the set of integers and the target sum and calls the "findSubsets" method to start the backtracking process.
  2. 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.
  3. 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.
  4. 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).
  5. If the recursive call returns without finding a subset

No comments:

Post a Comment

Divide and Conquer

Divide and conquer is a problem-solving technique in computer science where a problem is divided into smaller sub-problems, solved independ...