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

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

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.

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

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

本题目的解法:

1. 先将长方形按照宽排序,如果宽度一样, 按照高度降序排列,即 wi < wj or wi == wj && hi > hj; 这样得到的序列,从宽度考虑,前面的肯定可以放入后面的;对于wi == wj && hi > hj是因为在宽度一致的情况下,将更高的放在前面,可以保证后面根据高度查找最长子序列的时候,将这种组合排除;

2. 然后根据高度查找可以嵌套的最长子序列即可;

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

猜你喜欢

转载自my.oschina.net/u/922297/blog/689220
今日推荐