Skip to content

Commit b93eb07

Browse files
authored
Create 1994.The-Number-of-Good-Subsets_v2.cpp
1 parent a92c391 commit b93eb07

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
class Solution {
2+
vector<int>primes = {2,3,5,7,11,13,17,19,23,29};
3+
long M = 1e9+7;
4+
public:
5+
int numberOfGoodSubsets(vector<int>& nums)
6+
{
7+
int n = primes.size();
8+
vector<long>dp(1<<n);
9+
dp[0] = 1;
10+
11+
unordered_map<int,int>Map;
12+
for (auto x: nums)
13+
Map[x]++;
14+
15+
int count1 = 0;
16+
for (auto p: Map)
17+
{
18+
int x = p.first;
19+
int count = p.second;
20+
21+
if (x==1) continue;
22+
int encode = encoding(x);
23+
if (encode==-1) continue;
24+
25+
for (int state=(1<<n)-1; state>=1; state--)
26+
{
27+
if (state-encode == (state^encode))
28+
dp[state] = (dp[state] + dp[state-encode]*count%M) % M;
29+
}
30+
}
31+
32+
long ret = 0;
33+
for (int state=1; state<(1<<n); state++)
34+
ret = (ret+dp[state])%M;
35+
36+
long power2 = 1;
37+
for (int i=0; i<Map[1]; i++)
38+
power2 = (power2 * 2) % M;
39+
40+
return ret * power2 % M;
41+
}
42+
43+
int encoding(int num)
44+
{
45+
int encode = 0;
46+
for (int i=0; i<primes.size(); i++)
47+
{
48+
if (num % primes[i] ==0)
49+
{
50+
encode += (1<<i);
51+
num /= primes[i];
52+
}
53+
if (num % primes[i]==0)
54+
return -1;
55+
}
56+
return encode;
57+
}
58+
};

0 commit comments

Comments
 (0)