WikiGalaxy

Personalize

Backtracking on Subset Sum Problem

Introduction:

The Subset Sum Problem is a classic algorithmic problem where the goal is to determine if there exists a subset of a given set of numbers whose sum is equal to a specified number. Backtracking is an effective approach to solve this problem by exploring all possible subsets and backtracking when a partial solution fails.

    Step 1: Start with an empty subset and a sum of zero.
    Step 2: For each number, decide to include it in the subset or not.
    Step 3: If the sum of the current subset equals the target sum, a solution is found.
    Step 4: If the sum exceeds the target or all numbers are considered, backtrack.
    Step 5: Repeat until all subsets are explored.
  

      import java.util.ArrayList;
      import java.util.List;

      public class SubsetSum {
          static void findSubsets(int[] nums, int target) {
              List current = new ArrayList<>();
              backtrack(nums, target, 0, current);
          }

          static void backtrack(int[] nums, int target, int start, List current) {
              if (target == 0) {
                  System.out.println(current);
                  return;
              }
              if (target < 0) return;

              for (int i = start; i < nums.length; i++) {
                  current.add(nums[i]);
                  backtrack(nums, target - nums[i], i + 1, current);
                  current.remove(current.size() - 1);
              }
          }

          public static void main(String[] args) {
              int[] nums = {3, 34, 4, 12, 5, 2};
              int target = 9;
              findSubsets(nums, target);
          }
      }
    

Explanation of Code:

The Java code defines a method `findSubsets` which initializes the backtracking process. The `backtrack` method recursively explores each subset by adding numbers to the current subset and checking if the target sum is reached. When a valid subset is found, it is printed. If the target becomes negative or all numbers are considered, the function backtracks by removing the last added number.

Console Output:

[4, 5]

[3, 4, 2]

logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025