9

Number of subsets with a given OR value

 3 years ago
source link: https://www.geeksforgeeks.org/number-of-subsets-with-a-given-or-value/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
Number of subsets with a given OR value
Number of subsets with a given OR value

Given an array arr[] of length N, the task is to find the number of subsets with a given OR value M.
Examples: 

Input: arr[] = {2, 3, 2} M = 3 
Output:
All possible subsets and there OR values are: 
{2} = 2 
{3} = 3 
{2} = 2 
{2, 3} = 2 | 3 = 3 
{3, 2} = 3 | 2 = 3 
{2, 2} = 2 | 2 = 2 
{2, 3, 2} = 2 | 3 | 2 = 3

Input: arr[] = {1, 3, 2, 2}, M = 5 
Output:

Approach: A simple approach is to solve the problem by generating all the possible subsets and then by counting the number of subsets with the given OR value. However, for smaller values of array elements, it can be solved using dynamic programming
Let’s look at the recurrence relation first. 

dp[i][curr_or] = dp[i + 1][curr_or] + dp[i + 1][curr_or | arr[i]] 

The above recurrence relation can be defined as the number of subsets of sub-array arr[i…N-1] such that ORing them with curr_or will yield the required OR value. 
The recurrence relation is justified as there are only paths. Either, take the current element and OR it with curr_or or ignore it and move forward.
Below is the implementation of the above approach: 

  • Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
#define maxN 20
#define maxM 64
// To store states of DP
int dp[maxN][maxM];
bool v[maxN][maxM];
// Function to return the required count
int findCnt(int* arr, int i, int curr, int n, int m)
{
// Base case
if (i == n) {
return (curr == m);
}
// If the state has been solved before
// return the value of the state
if (v[i][curr])
return dp[i][curr];
// Setting the state as solved
v[i][curr] = 1;
// Recurrence relation
dp[i][curr]
= findCnt(arr, i + 1, curr, n, m)
+ findCnt(arr, i + 1, (curr | arr[i]), n, m);
return dp[i][curr];
}
// Driver code
int main()
{
int arr[] = { 2, 3, 2 };
int n = sizeof(arr) / sizeof(int);
int m = 3;
cout << findCnt(arr, 0, 0, n, m);
return 0;
}
Output
4

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK