Given an array of integers and a target sum, find the number of subsets that sum up to the target sum.
arr[]
and a target sum target
.- Input:
arr = [1, 2, 3, 3]
,target = 6
- Output:
2
(Subsets[1, 2, 3]
and[3, 3]
have a sum of 6)
Solution:
Count of Subsets with Given Sum
javapublic class SubsetSumCount { public static int countSubsets(int[] arr, int target) { int[][] dp = new int[arr.length + 1][target + 1]; // Initialize for (int i = 0; i <= arr.length; i++) { dp[i][0] = 1; } // Fill the dp table for (int i = 1; i <= arr.length; i++) { for (int j = 1; j <= target; j++) { if (arr[i - 1] <= j) { dp[i][j] = dp[i - 1][j] + dp[i - 1][j - arr[i - 1]]; } else { dp[i][j] = dp[i - 1][j]; } } } return dp[arr.length][target]; } public static void main(String[] args) { int[] arr = {1, 2, 3, 3}; int target = 6; System.out.println(countSubsets(arr, target)); // Output: 2 } }
Comments
Post a Comment