LeetCode[435] 无重叠区间

https://leetcode.cn/problems/non-overlapping-intervals/description/

线性dp

TLE

class Solution {
public:
    int f[200010];
    int a[200010];
    int eraseOverlapIntervals(vector<vector<int>> &intervals)
    {
        int n = intervals.size();
        sort(intervals.begin(), intervals.end(), [](const auto &u, const auto &v)
             { return u[0] < v[0]; });
        int ans = 0;
        for (int i = 0; i < n; i++)
        {
            f[i] = 1;
            for (int j = 0; j < i; j++)
            {
                if (intervals[j][1] <= intervals[i][0]) {
                    f[i] = max(f[i], f[j] + 1);
                }
            }
            ans = max(ans, f[i]);
        }

        cout << ans << endl;

        return n - ans;
    }
};

贪心

按照右端点从小到大排序。先选择右端点小的,能够留下更多的未覆盖区域。是最优解

证明:待补充(2022-11-23)

AC

class Solution {
public:
    int f[200010];
    int a[200010];
    int eraseOverlapIntervals(vector<vector<int>> &intervals)
    {
        int n = intervals.size();
        sort(intervals.begin(), intervals.end(), [](const auto &u, const auto &v)
             { return u[1] < v[1]; });
        
        int ans = 1;
        int r = intervals[0][1];
        
        for (int i = 1; i < n; i++)
        {
            if (intervals[i][0] >= r) {
                ans++;
                r = intervals[i][1];
            }
        }

        cout << ans << endl;

        return n - ans;
    }
};
posted @ 2022-11-23 11:43  星星亮了欸  阅读(31)  评论(0编辑  收藏  举报