題目鏈接:leetcode898
dp[i]表示以A[i]爲結尾的序列的區間或的不同個數,它肯定能夠由之前的狀態或上A[i]值會改變的所有狀態傳遞過來
也就是說,之前的狀態需要去重,可以用上一個集合去重,最好輸出集合的個數即dp要求的最終狀態
注意這個狀態一定是連續的!!
優化,由於或的特性,之後的狀態與前面的狀態不同一定是產生了更大的數才需要更新否則不更新
通過單調性優化的思路目前自己還想不到,貼個高效率的代碼日後補!
1s+代碼:
class Solution {
public:
int subarrayBitwiseORs(vector<int>& A) {
int n=A.size();
if(n==0) return 0;
unordered_set<int> ans; //ans存全局的不同數 pre存上一個狀態的所有起點的不同數
deque<int> ;
for(int i=0; i<n; i++) {
ans.insert(A[i]);
pre = cur;
}
return ans.size();
}
};
單調性優化:
class Solution {
public int subarrayBitwiseORs(int[] A) {
Set<Integer> ans = new HashSet();
Set<Integer> cur = new HashSet();
cur.add(0);
for (int x: A) {
Set<Integer> cur2 = new HashSet();
for (int y: cur)
cur2.add(x | y);
cur2.add(x);
cur = cur2;
ans.addAll(cur);
}
return ans.size();
}
}