-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgoodSubsets.txt
60 lines (52 loc) · 2.19 KB
/
goodSubsets.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
1994. The Number of Good Subsets
You are given an integer array nums.
We call a subset of nums good if its product can be represented as a product of one or more distinct prime numbers.
For example, if nums = [1, 2, 3, 4]:
[2, 3], [1, 2, 3], and [1, 3] are good subsets with products 6 = 2*3, 6 = 2*3, and 3 = 3 respectively.
[1, 4] and [4] are not good subsets with products 4 = 2*2 and 4 = 2*2 respectively.
Return the number of different good subsets in nums modulo 109 + 7.
A subset of nums is any array that can be obtained by deleting some (possibly none or all) elements from nums.
Two subsets are different if and only if the chosen indices to delete are different.
class Solution {
public:
vector<int> primes = {2,3,5,7,11,13,17,19,23,29};
long mod = 1e9 + 7;
int createMask(int num) {
int mask = 0,curr;
while(num != 1) {
for(int i = 0; i < primes.size(); i++){
if(num % primes[i] == 0){
curr = (1<<i);
if((mask & curr) != 0) return -1;
mask |= curr;
num /= primes[i];
break;
}
}
}
return mask;
}
int helper(int i, vector<vector<int>> &dp, vector<int> &cnt, vector<int> &m, int mask){
if(i == 31) return (mask != 0);
if(dp[i][mask] != -1) return dp[i][mask];
if(cnt[i] == 0 || m[i] == -1) return dp[i][mask] = helper(i+1,dp,cnt,m,mask) % mod;
long long res = 0;
if((mask & m[i]) == 0) res = ((long long)helper(i+1,dp,cnt,m,mask | m[i]) * cnt[i]) % mod;
res = (res + helper(i+1,dp,cnt,m,mask)) % mod;
return dp[i][mask] = res % mod;
}
int numberOfGoodSubsets(vector<int>& nums) {
vector<int> primeMask(31,0);
vector<int> cnt(31,0);
vector<vector<int>> dp(31,vector<int>((1<<11)-1,-1));
for(auto &i : nums) cnt[i]++;
for(int i = 1; i < 31; i++){
primeMask[i] = createMask(i);
}
primeMask[1] = -1;
long long res = helper(2,dp,cnt,primeMask,0);
long long op = 1;
for(int i = 0 ; i < cnt[1]; i++) op = (op * 2) % mod;
return (res * op) % mod;
}
};