LeetCode898子数组按位异或操作(单调型动态规划)

题目链接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();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章