|
| 1 | +/** |
| 2 | + * 1994. The Number of Good Subsets |
| 3 | + * https://leetcode.com/problems/the-number-of-good-subsets/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given an integer array nums. We call a subset of nums good if its product can be |
| 7 | + * represented as a product of one or more distinct prime numbers. |
| 8 | + * |
| 9 | + * - For example, if nums = [1, 2, 3, 4]: |
| 10 | + * - [2, 3], [1, 2, 3], and [1, 3] are good subsets with products 6 = 2*3, 6 = 2*3, and 3 = 3 |
| 11 | + * respectively. |
| 12 | + * - [1, 4] and [4] are not good subsets with products 4 = 2*2 and 4 = 2*2 respectively. |
| 13 | + * |
| 14 | + * Return the number of different good subsets in nums modulo 109 + 7. |
| 15 | + * |
| 16 | + * A subset of nums is any array that can be obtained by deleting some (possibly none or all) |
| 17 | + * elements from nums. Two subsets are different if and only if the chosen indices to delete |
| 18 | + * are different. |
| 19 | + */ |
| 20 | + |
| 21 | +/** |
| 22 | + * @param {number[]} nums |
| 23 | + * @return {number} |
| 24 | + */ |
| 25 | +var numberOfGoodSubsets = function(nums) { |
| 26 | + const MOD = 1e9 + 7; |
| 27 | + const primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]; |
| 28 | + const freq = new Array(31).fill(0); |
| 29 | + for (const num of nums) { |
| 30 | + freq[num]++; |
| 31 | + } |
| 32 | + |
| 33 | + const dp = new Array(1 << primes.length).fill(0); |
| 34 | + dp[0] = 1; |
| 35 | + for (let i = 0; i < freq[1]; i++) { |
| 36 | + dp[0] = (dp[0] * 2) % MOD; |
| 37 | + } |
| 38 | + |
| 39 | + for (let num = 2; num <= 30; num++) { |
| 40 | + if (freq[num] === 0) continue; |
| 41 | + let mask = 0; |
| 42 | + let valid = true; |
| 43 | + for (let i = 0; i < primes.length; i++) { |
| 44 | + let count = 0; |
| 45 | + let temp = num; |
| 46 | + while (temp % primes[i] === 0) { |
| 47 | + count++; |
| 48 | + temp /= primes[i]; |
| 49 | + } |
| 50 | + if (count > 1) { |
| 51 | + valid = false; |
| 52 | + break; |
| 53 | + } |
| 54 | + if (count === 1) { |
| 55 | + mask |= 1 << i; |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + if (!valid) continue; |
| 60 | + |
| 61 | + const prev = dp.slice(); |
| 62 | + for (let j = 0; j < 1 << primes.length; j++) { |
| 63 | + if ((j & mask) === 0) { |
| 64 | + dp[j | mask] = (dp[j | mask] + prev[j] * freq[num]) % MOD; |
| 65 | + } |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + let result = 0; |
| 70 | + for (let i = 1; i < 1 << primes.length; i++) { |
| 71 | + result = (result + dp[i]) % MOD; |
| 72 | + } |
| 73 | + |
| 74 | + return result; |
| 75 | +}; |
0 commit comments