1、题目
We have an array A
of non-negative integers.
For every (contiguous) subarray B = [A[i], A[i+1], ..., A[j]]
(with i <= j
), we take the bitwise OR of all the elements in B
, obtaining a result A[i] | A[i+1] | ... | A[j]
.
Return the number of possible results. (Results that occur more than once are only counted once in the final answer.)
Example 1:
Input: [0]
Output: 1
Explanation:
There is only one possible result: 0.
Example 2:
Input: [1,1,2]
Output: 3
Explanation:
The possible subarrays are [1], [1], [2], [1, 1], [1, 2], [1, 1, 2].
These yield the results 1, 1, 2, 1, 3, 3.
There are 3 unique values, so the answer is 3.
Example 3:
Input: [1,2,4]
Output: 6
Explanation:
The possible results are 1, 2, 3, 4, 6, and 7.
Note:
1 <= A.length <= 50000
0 <= A[i] <= 10^9
2、分析
这个题出在动态规划的栏目里,一开始想了半天如何递推,最后抱着试一试的心态暴力了以下,结果过了。
由于是运算,将整个数组一个一个或起来的结果一定是所有子串的或运算结果中最大的一个。我们可以事先将整个最大结果记录下来。然后开始暴力求接,遍历所有可能的子串,求出他们或运算的结果,最终返回不同的结果的个数。其中在计算以下标i开头的所有子串的或运算结果时,如果已经达到了最大值,则以i开头的子串的情况就可以结束了,因为就算再延长j,或运算的结果也不会再改变了。去重的话直接使用set来实现。
3、代码
class Solution {
public:
int subarrayBitwiseORs(vector<int>& A) {
set<int> result;
int s = A.size();
int maxx=0,temp=0;
for(int i=0;i<s;i++)
{
result.insert(A[i]);
temp|=A[i];
result.insert(temp);
if(temp>maxx) maxx = temp;
}
for(int i=0;i<s;i++)
{
int n = A[i];
for(int j=i+1;j<s;j++)
{
n |= A[j];
result.insert(n);
if(n==maxx) break;
}
}
return result.size();
}
};