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].
这道题,我的思路就是按照数组中第一个元素的大小来先排个序。然后对于集合中的每个数组,都计算以它开始的链表最大长度。这样一步步递归,并且用一个记忆map来储存已算过的数组索引。
package leetcode;
import java.util.Arrays;
import java.util.HashMap;
public class Maximum_Length_of_Pair_Chain_646 {
public int findLongestChain(int[][] pairs) {
Arrays.sort(pairs,(a,b) -> a[0]==b[0]? a[1]-b[1] : a[0]-b[0]);
HashMap<Integer, Integer> map=new HashMap<Integer, Integer>();
int longest=0;
for(int i=0;i<pairs.length;i++){
int count=longestChainFromThisIndex(pairs, i, map);
if(count>longest){
longest=count;
}
}
return longest;
}
//从该index开始的最大链长度(包含该index)
public int longestChainFromThisIndex(int[][] pairs,int index,
HashMap<Integer, Integer> map){
if(index==pairs.length){
return 0;
}
if(map.get(index)!=null){
return map.get(index);
}
int end=pairs[index][1];
int pointer=index+1;
while(pointer<pairs.length&&pairs[pointer][0]<=end){
pointer++;
}
int nextLongest=0;
for(int i=pointer;i<pairs.length;i++){
int theLong=longestChainFromThisIndex(pairs, i, map);
if(theLong>nextLongest){
nextLongest=theLong;
}
}
int count=1+nextLongest;
map.put(index, count);
return count;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Maximum_Length_of_Pair_Chain_646 m=new Maximum_Length_of_Pair_Chain_646();
int[][] pairs=new int[][]{
{-7, -1}, {0, 10}, {2, 3}, {3, 6}, {3, 10}, {4, 5}, {7, 9}, {7, 9}
};
System.out.println(m.findLongestChain(pairs));
}
}
当然,这样子的时间复杂度不太好,勉勉强强AC了。
有大神说,无论是按照数组的第一个元素排序,还是按照数组的第二个元素排序,这个问题都能转化为用DP解决。
以下是用DP解决的。dp[i]储存的是从i结束的链表长度最大值。首先初始化每个dp[i]为1。然后对于每个dp[i],找在 i 前面的索引 0~j,如果存在可以链接在i 前面的数组,且加完后大于dp[i]之前的值,那么则在dp[j]的基础上+1.
public 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;
}
}
如果想使用Greedy来解决这个问题,那么只能是按照数组的第二个元素排序。(按照数组的第一个元素排序将会行不通)。如 (8,9) (10,11) (1,100)。
按照数组第一个元素排序: (1,100),(8,9), (10,11) 。不能通过比较 [i][end] 和 [i+1][begin] 来增加链。
而如果按照数组第二个元素排序: (8,9) ,(10,11), (1,100),那么则可以通过比较 [i][end] 和 [i+1][begin] 来增加链。
public int findLongestChain(int[][] pairs)
{
Arrays.sort(pairs, (a,b) -> a[1] - b[1]);
int count = 0, end = Integer.MIN_VALUE;
for (int[] pair : pairs)
{
if (pair[0] > end)
{
count++;
end = pair[1];
}
}
return count;
}