** Leetcode 646. Maximum Length of Pair Chain | dp

https://leetcode.com/problems/maximum-length-of-pair-chain/description/

sort + LIS

O(n^2)版本

bool cmp(const vector<int>&a, const vector<int>&b) {
    // if (a[0] != b[0]) return a[1] < b[1];
    // else return a[0] < b[0];
    
    if (a[1] < b[0]) return 1;
    if (a[0] > b[1]) return 0;
    return a[0] < b[0];
    
    // if (a[1] != b[0])
    // return a[1] < b[0];
    // else {
    //     if (a[0] > b[1]) {
    //         return 0;
    //     }
    //     return a[0] < b[0];
    // }
        
}

class Solution {
public:
    int findLongestChain(vector< vector<int> >& pairs) {
        sort( pairs.begin(), pairs.end(), cmp );
        vector<int>dp( pairs.size(), 0 );
        int ret = 0;
        for (int i = 0; i < pairs.size(); i++) {
            // printf( "a[%d]=%d,%d\n", i, pairs[i][0], pairs[i][1] );
            if (i == 0) {
                dp[i] = 1;
            } else {
                dp[i] = 1;
                for (int k = 0; k < i; k++) {
                    if ( pairs[k][1] < pairs[i][0] ) {
                        dp[i] = max(dp[i], dp[k] + 1  );
                    } 
                    // dp[i] = max(dp[i], dp[k] + ( cmp(pairs[k], pairs[i]) ) );
                }
            }
            ret = max(dp[i], ret);
        }
        return ret;
    }
};

nlogn版本

https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings/description/

这里看到的

public int findLongestChain(int[][] pairs) {
    Arrays.sort(pairs, (a,b) -> a[1] - b[1]);
    int sum = 0, n = pairs.length, i = -1;
    while (++i < n) {
        sum++;
        int curEnd = pairs[i][1];
        while (i+1 < n && pairs[i+1][0] <= curEnd) i++;
    }
    return sum;
}



猜你喜欢

转载自blog.csdn.net/u011026968/article/details/80977312