| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 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.CountNumberOfMaximumBitwiseORSubsets; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class CountNumberOfMaximumBitwiseORSubsetsBacktracking : ICountNumberOfMaximumBitwiseORSubsets |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(2^n) |
| | 19 | | /// Space complexity - O(n) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="nums"></param> |
| | 22 | | /// <returns></returns> |
| | 23 | | public int CountMaxOrSubsets(int[] nums) |
| 3 | 24 | | { |
| 3 | 25 | | var maxOr = 0; |
| 3 | 26 | | var count = 0; |
| | 27 | |
|
| 12 | 28 | | maxOr = nums.Aggregate(maxOr, (current, num) => current | num); |
| | 29 | |
|
| 3 | 30 | | CountMaxOrSubsetsHelper(nums, 0, 0, ref maxOr, ref count); |
| | 31 | |
|
| 3 | 32 | | return count; |
| 3 | 33 | | } |
| | 34 | |
|
| | 35 | | private static void CountMaxOrSubsetsHelper(int[] nums, int index, int currentOr, ref int maxOr, ref int count) |
| 53 | 36 | | { |
| 53 | 37 | | if (index == nums.Length) |
| 28 | 38 | | { |
| 28 | 39 | | if (currentOr == maxOr) |
| 15 | 40 | | { |
| 15 | 41 | | count++; |
| 15 | 42 | | } |
| | 43 | |
|
| 28 | 44 | | return; |
| | 45 | | } |
| | 46 | |
|
| 25 | 47 | | CountMaxOrSubsetsHelper(nums, index + 1, currentOr | nums[index], ref maxOr, ref count); |
| | 48 | |
|
| 25 | 49 | | CountMaxOrSubsetsHelper(nums, index + 1, currentOr, ref maxOr, ref count); |
| 53 | 50 | | } |
| | 51 | | } |