I was asked to count the number of subsets with sum == target but the caveat was that I can include a particular element in exactly 1 subset.
E.g : A = [2,2,3], target = 5
Output is 1 [2,3]....... not 2 [2,3], [2,3]
I came up with this recursive approach but was unable to avoid the duplicates.
My solution returns 2 instead of 1, even though I am using the visited[] array
public int countSubsets(int[] A, int target) {
return countOfSubsetsWithGivenSum(0, 0, target, A, new boolean[A.length]);
}
private int countOfSubsetsWithGivenSum(int start, int sum, int target, int[] A, boolean[] visited) {
if (sum == target) return 1 + countOfSubsetsWithGivenSum(0, 0, target, A, visited);
if (start >= A.length || sum > target) return 0;
int count = 0;
for (int i=start; i<A.length; i++) {
if (!visited[i]) {
visited[i] = true;
count += countOfSubsetsWithGivenSum(i+1, sum + A[i], target, A, visited);
visited[i] = false;
}
}
return count;
}Let me know where I'm missing out or is there any better approach?
Any help would be appreciated!
Comments (3)


