Skip to content

2044. Count Number of Maximum Bitwise-OR Subsets 👍

  • Time: $O(2^n)$
  • Space: $O(2^n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
 public:
  int countMaxOrSubsets(vector<int>& nums) {
    const int ors = accumulate(nums.begin(), nums.end(), 0, bit_or<>());
    int ans = 0;
    dfs(nums, 0, 0, ors, ans);
    return ans;
  }

 private:
  void dfs(const vector<int>& nums, int i, int path, const int& ors, int& ans) {
    if (i == nums.size()) {
      if (path == ors)
        ++ans;
      return;
    }

    dfs(nums, i + 1, path, ors, ans);
    dfs(nums, i + 1, path | nums[i], ors, ans);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
  public int countMaxOrSubsets(int[] nums) {
    final int ors = Arrays.stream(nums).reduce((a, b) -> a | b).getAsInt();
    dfs(nums, 0, 0, ors);
    return ans;
  }

  private int ans = 0;

  private void dfs(int[] nums, int i, int path, final int ors) {
    if (i == nums.length) {
      if (path == ors)
        ++ans;
      return;
    }

    dfs(nums, i + 1, path, ors);
    dfs(nums, i + 1, path | nums[i], ors);
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution:
  def countMaxOrSubsets(self, nums: list[int]) -> int:
    ors = functools.reduce(operator.or_, nums)
    ans = 0

    def dfs(i: int, path: int) -> None:
      nonlocal ans
      if i == len(nums):
        if path == ors:
          ans += 1
        return

      dfs(i + 1, path)
      dfs(i + 1, path | nums[i])

    dfs(0, 0)
    return ans