Given an array of integers and a target sum, find all unique subsets that sum up to the target sum, considering each number in the array can be used multiple times.

 Subset Sum Problem with Multiple Solutions

  • Description: Given an array of integers and a target sum, find all unique subsets that sum up to the target sum, considering each number in the array can be used multiple times.
  • Input: An array of integers arr[] and a target sum target.
  • Output: Return a list of lists containing all unique subsets that sum up to the target sum.
  • Example:
    • Input: arr = [2, 3, 7], target = 7
    • Output: [[2, 2, 3], [7]]


  • Subset Sum Problem with Multiple Solutions

    java
    import java.util.ArrayList; import java.util.List; public class MultipleSubsetSum { public static List<List<Integer>> findSubsets(int[] arr, int target) { List<List<Integer>> result = new ArrayList<>(); findSubsetsRecursive(arr, target, new ArrayList<>(), result); return result; } private static void findSubsetsRecursive(int[] arr, int target, List<Integer> current, List<List<Integer>> result) { if (target == 0) { result.add(new ArrayList<>(current)); return; } if (target < 0) return; for (int num : arr) { current.add(num); findSubsetsRecursive(arr, target - num, current, result); current.remove(current.size() - 1); } } public static void main(String[] args) { int[] arr = {2, 3, 7}; int target = 7; List<List<Integer>> subsets = findSubsets(arr, target); for (List<Integer> subset : subsets) { System.out.println(subset); } // Output: [2, 2, 3], [7] } }

  • Comments

    Popular posts from this blog

    Today Walkin 14th-Sept

    Spring Elasticsearch Operations

    Hibernate Search - Elasticsearch with JSON manipulation