LeetCode - Maximum Length Of Pair Chain(算法)

算法概论之LeetCode- Maximum Length Of Pair Chain


1. 题目描述

You are given n pairs of numbers. In every pair, the first number is always smaller than the second number.

Now, we define a pair (c, d) can follow another pair (a, b) if and only if b < c. Chain of pairs can be formed in this fashion.

Given a set of pairs, find the length longest chain which can be formed. You needn’t use up all the given pairs. You can select pairs in any order.
给定一些两个数组成的对a,<的定义为后一个数对的第一个数大于前一个数对的第二个数,即an+1 > an
求递增数对的最大长度。(嘻嘻,是不是就是递增子序列的变样吗

2. 样例输入输出

Input: [[1,2], [2,3], [3,4]]
Output: 2
Explanation: The longest chain is [1,2] -> [3,4]

3. 算法描述

参考上一篇博客的做法。zyq的动态规划
1. 状态是什么
2. 状态转移方程是什么
3. 状态的初始值是什么
4. 问题要求的最后答案是什么
每个步骤分析完成之后,就基本上解决了整道动态规划的问题。

dp[ pair[i] ]表示以pair[i]结尾的子序列中LIS的长度。
然后我用dp[ pair[j] ] (pair[j]”小于”pair[i] ) 来表示在pair[i]之前的LIS的长度。

然后我们可以看到,只有当pair[i]”小于” pair[j]的时候,我们需要进行判断,是否将pair[i]加入到dp [ pair[j] ]当中。

如果写成递推公式,我们可以得到dp[ pair[i] ] = max(dp[ pair[j] ](0 <=j < i)) + (a[i]>a[j]?1:0)。 于是我们就能够得到O(n^2)的动态规划方法的实现:

这样就出问题了。。。

因为保证不了,[3 4] [8 9] [-1 -2] ;
这样的话,我们可以使得第一个dp=1,第二个dp =2 ,第三个dp = 1. 得不到我们要的答案 max= 3;

因为我们需要这个序列有序,不然解决不了。


class Solution {
    public int findLongestChain(int[][] pairs) {
        Arrays.sort(pairs, (a, b) -> (a[0] - b[0]));  
        int i, j, max = 0, n = pairs.length;  
        int dp[] = new int[n];  
        for (i = 0; i < n; i++) dp[i] = 1;  
        for (i = 1; i < n; i++)  
            for (j = 0; j < i; j++)  
                if (pairs[j][1] < pairs[i][0] && dp[i] < dp[j] + 1)  
                    dp[i] = dp[j] + 1;  
       for (i = 0; i < n; i++) if (max < dp[i]) max = dp[i]; 
    return max;  
    }
}

这是最愚蠢的思路,两个排序都可以,以pair的第一个数为序,或者第二个数为序都可以。


观摩学习

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;
}

上述代码时间复杂度O(nlogn).

这道题很类似于我们的时间段分配问题。上面的解答就是使用了贪心算法。

Prove by exchange:
Let C be the pair chain of the maximum length, C[p] be the p-th pair in C. Suppose there is a pair q such that q[0] > C[p-1][1] and q[1] <= C[p][1]. We replace C[p] with q, the resulting pair chain will not be shorter than the original C. Therefore, we can do such replacement as many as we want.

Whenever the inner while loop is complete, i points to the last pair that is not supposed to be in the chain. ++i increments i right away so it points to the next pair belongs to the chain.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值