diff --git a/C#/the-number-of-beautiful-subsets.cs b/C#/the-number-of-beautiful-subsets.cs new file mode 100644 index 0000000..1222808 --- /dev/null +++ b/C#/the-number-of-beautiful-subsets.cs @@ -0,0 +1,38 @@ +/** + * time O(n) + * space O(n) + */ + +public class Solution { + public int BeautifulSubsets(int[] nums, int k) { + Dictionary cnt = new Dictionary(); + foreach (int x in nums) { + if (cnt.ContainsKey(x)) { + cnt[x]++; + } else { + cnt[x] = 1; + } + } + + Func count = (int x) => { + int y = x; + while (cnt.ContainsKey(y - k)) { + y -= k; + } + List dp = new List { 1, 0 }; + for (int i = y; i <= x; i += k) { + dp = new List { dp[0] + dp[1], dp[0] * ((1 << cnt[i]) - 1) }; + } + return dp[0] + dp[1]; + }; + + int result = 1; + foreach (var kvp in cnt) { + int i = kvp.Key; + if (!cnt.ContainsKey(i + k)) { + result *= count(i); + } + } + return result - 1; + } +}