【leetcode编程题目354】俄罗斯套娃

来自 https://leetcode.com/problems/russian-doll-envelopes/ide

You have a number of envelopes with widths and heights given as a pair of integers (w, h). One envelope can fit into another if and only if both the width and height of one envelope is greater than the width and height of the other envelope.code

What is the maximum number of envelopes can you Russian doll? (put one inside other)排序

Example:
Given envelopes = [[5,4],[6,4],[6,7],[2,3]], the maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]).ip

 

这个题目是最长子序列的变形;最长子序列能够参考https://en.wikipedia.org/wiki/Longest_increasing_subsequenceleetcode

本题目的解法:it

1. 先将长方形按照宽排序,若是宽度同样, 按照高度降序排列,即 wi < wj or wi == wj && hi > hj; 这样获得的序列,从宽度考虑,前面的确定能够放入后面的;对于wi == wj && hi > hj是由于在宽度一致的状况下,将更高的放在前面,能够保证后面根据高度查找最长子序列的时候,将这种组合排除;class

2. 而后根据高度查找能够嵌套的最长子序列便可;im

 

 

func maxEnvelopes(envelopes [][]int) int {
	sort.Sort(byShape(envelopes))

	m := make([]int, len(envelopes)+1, len(envelopes)+1)
	L := 0
	for i, a := range envelopes {
		lo, hi := 1, L
		for lo <= hi {
			mid := (lo + hi) / 2
			b := envelopes[m[mid]]
			if b[1] < a[1] {
				lo = mid + 1
			} else {
				hi = mid - 1
			}
		}

		m[lo] = i
		if L < lo {
			L = lo
		}
	}

	return L
}

type byShape [][]int

func (a byShape) Len() int {
	return len(a)
}

func (a byShape) Less(i, j int) bool {
	if a[i][0] != a[j][0] {
		return a[i][0] < a[j][0]
	}

	return a[j][1] < a[i][1]
}

func (a byShape) Swap(i, j int) {
	a[i], a[j] = a[j], a[i]
}
相关文章
相关标签/搜索