354. Russian Doll Envelopes

You have a number of envelopes with widths and heights given as a pair of integers (w, h). One envelope can fit into another if and only if both the width and height of one envelope is greater than the width and height of the other envelope.

What is the maximum number of envelopes can you Russian doll? (put one inside other)

Note: Rotation is not allowed.

Example:

Input: [[5,4],[6,4],[6,7],[2,3]]
Output: 3 
Explanation: The maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]).

Dynamic programming算是brute force解。

// Dynamic Programming
int maxEnvelopes(vector<vector<int>>& envelopes) { // time: O(n^2); space: O(n)
    if (envelopes.empty()) return 0;
    sort(envelopes.begin(), envelopes.end());
    int n = envelopes.size();
    // int res = 0;
    vector<int> len(n, 1);
    for (int i = 0; i < n; ++i) {
        for (int j = i - 1; j >= 0; --j) {
            if (envelopes[i][0] > envelopes[j][0] && envelopes[i][1] > envelopes[j][1])
                len[i] = max(len[i], len[j] + 1);
        }
        // res = max(res, len[i]);
    }
    return *max_element(len.begin(), len.end());
}

也可以利用先前在Longest Increasing Subsequence中用到的Binary Search來提昇效率到O(nlogn)。先把envelopes照寬度由小到大排序,如果寬度一樣,則照高度由大到小排序。這是因為這個演算法讓同一個寬度中保留最小的高度高於前一個寬度信封的高度。

// Binary Search with lower_bound
int maxEnvelopes(vector<vector<int>>& envelopes) { // time: O(nlogn); space: O(n)
    if (envelopes.empty()) return 0;
    sort(envelopes.begin(), envelopes.end(), [](const vector<int>& a, const vector<int>& b) {
        return a[0] < b[0] || (a[0] == b[0] && a[1] > b[1]);
    });
    vector<int> tmp; // only store heights
    for (auto& e : envelopes) {
        auto it = lower_bound(tmp.begin(), tmp.end(), e[1]); // find the first height not less than current height
        if (it == tmp.end()) tmp.push_back(e[1]);
        else if (*it > e[1]) *it = e[1];
    }
    return tmp.size();
}
// Binary Search with lower_bound
int maxEnvelopes(vector<vector<int>>& envelopes) { // time: O(nlogn); space: O(n)
    if (envelopes.empty()) return 0;
    sort(envelopes.begin(), envelopes.end(), [](const vector<int>& a, const vector<int>& b) {
        return a[0] < b[0] || (a[0] == b[0] && a[1] > b[1]);
    });
    vector<int> tmp; // only store heights
    int n = envelopes.size();
    for (int i = 0; i < n; ++i) {
        int l = 0, r = tmp.size();
        while (l < r) {
            int mid = l + (r - l) / 2;
            if (tmp[mid] < envelopes[i][1]) l = mid + 1;
            else r = mid;
        }
        if (l == tmp.size()) tmp.push_back(envelopes[i][1]);
        else if (tmp[l] > envelopes[i][1]) tmp[l] = envelopes[i][1];
    }
    return tmp.size();
}
300. Longest Increasing Subsequence673. Number of Longest Increasing Subsequence674. Longest Continuous Increasing Subsequence

Last updated

Was this helpful?