Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- https://leetcode.com/problems/the-number-of-good-subsets/
- https://practice.geeksforgeeks.org/problems/cec5db442a5652d07dd41e37ea780345f08c9a3d/1
- 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.
- Example 1:
- Input: nums = [1,2,3,4]
- Output: 6
- Explanation: The good subsets are:
- - [1,2]: product is 2, which is the product of distinct prime 2.
- - [1,2,3]: product is 6, which is the product of distinct primes 2 and 3.
- - [1,3]: product is 3, which is the product of distinct prime 3.
- - [2]: product is 2, which is the product of distinct prime 2.
- - [2,3]: product is 6, which is the product of distinct primes 2 and 3.
- - [3]: product is 3, which is the product of distinct prime 3.
- Example 2:
- Input: nums = [4,2,3,15]
- Output: 5
- Explanation: The good subsets are:
- - [2]: product is 2, which is the product of distinct prime 2.
- - [2,3]: product is 6, which is the product of distinct primes 2 and 3.
- - [2,15]: product is 30, which is the product of distinct primes 2, 3, and 5.
- - [3]: product is 3, which is the product of distinct prime 3.
- - [15]: product is 15, which is the product of distinct primes 3 and 5.
- Constraints:
- 1 <= nums.length <= 10^5
- 1 <= nums[i] <= 30
- ---------------------------------------------------------------------------------------------------------------------------------------
- class Solution {
- public:
- vector<int> prime={2,3,5,7,11,13,17,19,23,29};
- int mod=1000000007;
- long long helper(int num, int mask, vector<int> &freq){
- if(num==31){
- return 1;
- }
- long long ans=0;
- ans=(ans+helper(num+1,mask,freq))%mod; //IGNORING NUMBER
- if(num%4!=0 && num%9!=0 && num%25!=0 && num%16!=0){
- int newMask=0;
- for(int i=0;i<prime.size();i++){
- if(num%prime[i]==0){
- newMask=newMask | (1<<prime[i]);
- }
- }
- if((newMask & mask)==0){
- ans=(ans+(helper(num+1,mask | newMask,freq)%mod*freq[num])%mod)%mod; // USE IT
- }
- }
- return ans%mod;
- }
- int numberOfGoodSubsets(vector<int>& nums) {
- vector<int> freq(31,0);
- int ones=1;
- for(auto x: nums){
- freq[x]++;
- if(x==1){
- ones=(ones%mod*2)%mod;
- }
- }
- int mask=0;
- long long ans=helper(2,mask,freq)-1;
- return (ans%mod*ones%mod)%mod;
- }
- };
- you can map 10 numbers to a new ranking to memoise the solution
Advertisement
Add Comment
Please, Sign In to add comment