Maximum_Length_of_Pair_Chain

题目描述:

  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.
    (给你一个pair对数组,若存在(a, b) (c, d) && b < c 那么就能构成一条链,求最长的链的长度)
Example 1:

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

Note:
    The number of given pairs will be in the range [1, 1000].

PS:这个pair对数对是在排序之后找最长链,第一次没有排序提交之后显示[[2,3],[3,4],[1,2]]的返回值为2,所以可知OJ系统判定是排序之后的最长链。

思路:典型动态规划的题目,递推式:chain[i] = Math.max(chain[i], chain[j]+1)和max = Math.max(max,chain[i])。chain[i]代表到包含i元素的最长链,max则是真正的最长链,第一个递推式的意思是如果i元素可以链在j元素上那么就把chain[i]就可以表示为chain[j]+1,并通过Math.max函数找该点的最大值,而第二个递推式则是在这些点中找最大链。

public class Maximum_Length_of_Pair_Chain {
	public static void sort(int a[][])
	{
		for(int i=0;i<a.length-1;i++)  
	        for(int j=0;j<a.length-1-i;j++) 
	            if(a[j][0]>a[j+1][0]) 
	            {
	                int t=a[j][0];
	                a[j][0]=a[j+1][0];  
	                a[j+1][0]=t;
	                t=a[j][1];
	                a[j][1]=a[j+1][1];  
	                a[j+1][1]=t;
	            }
	}
	public static int findLongestChain(int[][] pairs) 
	{
		if(pairs.length == 0||pairs == null)
			return 0;
		sort(pairs);
		int max = 1;
		int chain[] = new int[pairs.length];
		for(int i=0;i<chain.length;i++)
			chain[i] = 1;
        for(int i=1;i<pairs.length;i++)
        {
        	for(int j=0;j<i;j++)
        	{
        		if(pairs[i][0]>pairs[j][1])
        			chain[i] = Math.max(chain[i], chain[j]+1);
        	}
        	max = Math.max(max,chain[i]);
        }
		return max;
    }
	public static void main(String[] args) {
		int pairs[][] = {{-6,9},{1,6},{8,10},{-1,4},{-6,-2},{-9,8},{-5,3},{0,3}};
		System.out.println(findLongestChain(pairs));
	}
}

本题和Largest_Divisible_Subset 是同一类型。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值