Microsoft | Interview question | Help Required
Difficulty: MEDIUMCategory: InterviewExperienceFrequency: 1Asked On 2024-03-23Added By Anonymous
Source: Link
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
1public int countSubsets(int[] A, int target) {
2 return countOfSubsetsWithGivenSum(0, 0, target, A, new boolean[A.length]);
3}
4private int countOfSubsetsWithGivenSum(int start, int sum, int target, int[] A, boolean[] visited) {
5 if (sum == target) return 1 + countOfSubsetsWithGivenSum(0, 0, target, A, visited);
6 if (start >= A.length || sum > target) return 0;
7
8 int count = 0;
9 for (int i=start; i<A.length; i++) {
10 if (!visited[i]) {
11 visited[i] = true;
12 count += countOfSubsetsWithGivenSum(i+1, sum + A[i], target, A, visited);
13 visited[i] = false;
14 }
15 }
16 return count;
17}Let me know where I'm missing out or is there any better approach?
Any help would be appreciated!