2044. 统计按位或能得到最大值的子集数目
DFS,每次考虑选择这个数或者不选。
时间复杂度:O(2n)O(2^n)O(2n)
空间复杂度:O(n)O(n)O(n)
class Solution {
public:
vector<int> a;
int maxn, ans;
void dfs(int u, int v) {
if (u == a.size()) {
if (v > maxn) {
maxn = v, ans = 1;
} else if (v == maxn) {
ans ++ ;
}
return ;
}
dfs(u + 1, v);
dfs(u + 1, v | a[u]);
}
int countMaxOrSubsets(vector<int>& nums) {
maxn = 0, ans = 0;
a = nums;
dfs(0, 0);
return ans;
}
};
本文介绍了一种使用深度优先搜索(DFS)解决的问题,即在给定整数数组中找到按位或运算能得到最大值的子集数目。通过递归实现的DFS算法,分析了时间复杂度为O(2^n)和空间复杂度为O(n),并提供了C++代码示例。

被折叠的 条评论
为什么被折叠?



