Skip to content

Commit 3a4011d

Browse files
author
weiy
committed
bitwise ORs of subarray contest medium
1 parent c87f1ff commit 3a4011d

File tree

1 file changed

+87
-0
lines changed

1 file changed

+87
-0
lines changed

DP/BitwiseORsOfSubarray.py

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
"""
2+
We have an array A of non-negative integers.
3+
4+
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].
5+
6+
Return the number of possible results. (Results that occur more than once are only counted once in the final answer.)
7+
8+
9+
10+
Example 1:
11+
12+
Input: [0]
13+
Output: 1
14+
Explanation:
15+
There is only one possible result: 0.
16+
Example 2:
17+
18+
Input: [1,1,2]
19+
Output: 3
20+
Explanation:
21+
The possible subarrays are [1], [1], [2], [1, 1], [1, 2], [1, 1, 2].
22+
These yield the results 1, 1, 2, 1, 3, 3.
23+
There are 3 unique values, so the answer is 3.
24+
Example 3:
25+
26+
Input: [1,2,4]
27+
Output: 6
28+
Explanation:
29+
The possible results are 1, 2, 3, 4, 6, and 7.
30+
31+
32+
对子数组进行或运算,最后结果是有多少个唯一的解。
33+
思路是DP:
34+
走的弯路:
35+
一开始写的:
36+
[1, 1, 2, 2, 4]
37+
A[0] = {1}
38+
基于A[0],判断是否在A[0]里,不在的话在添加,在的话就继承A[0]。
39+
A[1] = {1}
40+
A[2] = {1, 2, 3}
41+
A[3] = {1, 2 ,3}
42+
运行到这里都没什么错误,因为就碰巧进行了一次相邻的或运算。
43+
A[4] = {1, 2, 3, 4, 5, 6, 7}
44+
到了这里就有了错误,4不应该与这么多进行或运算。
45+
46+
这里就不知道怎么做了,如果要把上一次的结果也加到里面,怎么才能保证所进行的或运算不包含不相邻的两个点如:
47+
[1, 2, 4]
48+
不会进行 [1,4]的运算。
49+
50+
重新的梳理应该是:
51+
[1]
52+
A[0] = {1}
53+
[ 1] [1, 1]
54+
A[1] = {1}
55+
注意,这里与上一个进行或运算,但不把上一个也存到A[2]里面,
56+
[ 2] [1, 1, 2] [ 1, 2]
57+
A[2] = {2, 3}
58+
基于上一个,但不会将上一个的结果加到本次里影响最终运算。
59+
---
60+
最终输出结果时,进行一次全部的set整理。
61+
62+
测试地址:
63+
https://leetcode.com/contest/weekly-contest-100/problems/bitwise-ors-of-subarrays/
64+
65+
Accepted.
66+
67+
68+
"""
69+
class Solution(object):
70+
def subarrayBitwiseORs(self, A):
71+
"""
72+
:type A: List[int]
73+
:rtype: int
74+
"""
75+
if not A:
76+
return 0
77+
78+
dp = [{A[0]}]
79+
80+
for i in range(1, len(A)):
81+
new = {A[i]}
82+
for j in dp[i-1]:
83+
new.add(j|A[i])
84+
dp.append(new)
85+
86+
return len(set.union(*dp))
87+

0 commit comments

Comments
 (0)