| | | 1 | | // -------------------------------------------------------------------------------- |
| | | 2 | | // Copyright (C) 2026 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | | 3 | | // All Rights Reserved. |
| | | 4 | | // -------------------------------------------------------------------------------- |
| | | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | | 9 | | // known as Yevhenii Yeriemeieiv). |
| | | 10 | | // -------------------------------------------------------------------------------- |
| | | 11 | | |
| | | 12 | | namespace LeetCode.Algorithms.TheNumberOfBeautifulSubsets; |
| | | 13 | | |
| | | 14 | | /// <inheritdoc /> |
| | | 15 | | public sealed class TheNumberOfBeautifulSubsetsBacktracking : ITheNumberOfBeautifulSubsets |
| | | 16 | | { |
| | | 17 | | /// <summary> |
| | | 18 | | /// Time complexity - O(n * 2^n) |
| | | 19 | | /// Space complexity - O(n) |
| | | 20 | | /// </summary> |
| | | 21 | | /// <param name="nums"></param> |
| | | 22 | | /// <param name="k"></param> |
| | | 23 | | /// <returns></returns> |
| | | 24 | | public int BeautifulSubsets(int[] nums, int k) |
| | 8 | 25 | | { |
| | 8 | 26 | | if (nums.Length <= 1) |
| | 1 | 27 | | { |
| | 1 | 28 | | return nums.Length; |
| | | 29 | | } |
| | | 30 | | |
| | 7 | 31 | | var count = 0; |
| | | 32 | | |
| | 7 | 33 | | Backtrack(nums, k, 0, new List<int>(), ref count); |
| | | 34 | | |
| | 7 | 35 | | return count - 1; |
| | 8 | 36 | | } |
| | | 37 | | |
| | | 38 | | private static void Backtrack(IReadOnlyList<int> nums, int k, int index, IList<int> subset, ref int count) |
| | 35101 | 39 | | { |
| | 94025 | 40 | | while (true) |
| | 94025 | 41 | | { |
| | 94025 | 42 | | if (index >= nums.Count) |
| | 35101 | 43 | | { |
| | 35101 | 44 | | count++; |
| | | 45 | | |
| | 35101 | 46 | | return; |
| | | 47 | | } |
| | | 48 | | |
| | 58924 | 49 | | if (!subset.Contains(nums[index] - k) && !subset.Contains(k + nums[index])) |
| | 35094 | 50 | | { |
| | 35094 | 51 | | subset.Add(nums[index]); |
| | | 52 | | |
| | 35094 | 53 | | Backtrack(nums, k, index + 1, subset, ref count); |
| | | 54 | | |
| | 35094 | 55 | | subset.RemoveAt(subset.Count - 1); |
| | 35094 | 56 | | } |
| | | 57 | | |
| | 58924 | 58 | | index += 1; |
| | 58924 | 59 | | } |
| | 35101 | 60 | | } |
| | | 61 | | } |