703269. Count subsets having distinct even numbers
Easy
Count Subsets Having Distinct Even Numbers
Summary
Given an array arr containing integers, write a program to count the number of subsets that have distinct even numbers. The problem requires us to find all possible subsets of the given array and then check if each subset contains only distinct even numbers.
Detailed Explanation
The problem can be solved by generating all possible subsets of the given array using recursion or dynamic programming. We will use the recursive approach here. For each subset, we will iterate through its elements and count the number of distinct even numbers.
Here's a step-by-step breakdown of the solution:
- Initialize a variable
countto store the total count of subsets with distinct even numbers. - Define a recursive function
countDistinctEvenSubsetsthat takes an arrayarr, an indexi, and a subsetsubset. - If
i >= arr.length, it means we have processed all elements in the array, so add1tocount(since this is a valid subset with distinct even numbers) and return. - For each possible value of
jfrom0toarr.length - i - 1, recursively callcountDistinctEvenSubsetswith the subarrayarr(i+1..i+j+1)and the updated subsetsubset + arr[i]. - If
j == 0, it means we are considering the empty set, so simply return without adding anything tocount. - After processing all subsets, return the final value of
count.
Time complexity: O(2^n), where n is the length of the array.
Space complexity: O(n), for storing the recursive function calls.
Optimized Solutions
Java
public class Main {
public static int countDistinctEvenSubsets(int[] arr) {
return countDistinctEvenSubsets(arr, 0, new ArrayList<>());
}
private static int countDistinctEvenSubsets(int[] arr, int i, List<Integer> subset) {
if (i >= arr.length) {
return 1;
}
int count = 0;
for (int j = 0; j <= arr.length - i - 1; j++) {
subset.add(arr[i]);
count += countDistinctEvenSubsets(arr, i + j + 1, subset);
subset.remove(subset.size() - 1);
}
return count;
}
public static void main(String[] args) {
int[] arr = {2, 4, 6};
System.out.println(countDistinctEvenSubsets(arr));
}
}