# 646. Maximum Length of Pair Chain

## 刷题内容

• https://leetcode.com/problems/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.

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].


## 解题方案

AC代码如下：

class Solution(object):
def findLongestChain(self, pairs):
"""
:type pairs: List[List[int]]
:rtype: int
"""
if not pairs or len(pairs) == 0:
return 0
pairs = sorted(pairs, key=lambda x:x[1])
res, i = 0, -1
while i + 1 < len(pairs):
res += 1
i += 1
cur_end = pairs[i][1]
while i + 1 < len(pairs) and pairs[i+1][0] <= cur_end:
i += 1
return res


class Solution(object):
def findLongestChain(self, pairs):
"""
:type pairs: List[List[int]]
:rtype: int
"""
if not pairs or len(pairs) == 0:
return 0
cur, res = float('-inf'), 0
for p in sorted(pairs, key=lambda x: x[1]):
if cur < p[0]: cur, res = p[1], res + 1
return res


class Solution(object):
def findLongestChain(self, pairs):
"""
:type pairs: List[List[int]]
:rtype: int
"""
if not pairs or len(pairs) == 0:
return 0
pairs = sorted(pairs, key=lambda x:x[0])
dp = [1] * len(pairs)
for i in range(1, len(pairs)):
for j in range(i):
dp[i] = max(dp[i], dp[j] + 1 if pairs[i][0] > pairs[j][1] else dp[j])
return dp[-1]


class Solution(object):
def findLongestChain(self, pairs):
"""
:type pairs: List[List[int]]
:rtype: int
"""
if not pairs or len(pairs) == 0:
return 0
pairs = sorted(pairs, key=lambda x:x[0])
dp = [1] * len(pairs)
for i in range(1, len(pairs)):
dp[i] = max([dp[j] + 1 if pairs[i][0] > pairs[j][1] else dp[j] for j in range(i)])
return dp[-1]


apachecn/AiLearning