[leetcode programming topic 354] Russian nesting doll

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

 

This topic is a variant of the longest subsequence; the longest subsequence can refer to https://en.wikipedia.org/wiki/Longest_increasing_subsequence

Solution to this problem:

1. First sort the rectangles by width. If the widths are the same, sort them in descending order of height, that is, wi < wj or wi == wj && hi > hj; For the sequence obtained in this way, considering the width, the former can definitely be placed in the latter; For wi == wj && hi > hj, it is because in the case of the same width, the higher one is placed in the front, which can ensure that this combination is excluded when searching for the longest subsequence based on the height later;

2. Then find the longest subsequence that can be nested according to the height;

 

 

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

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325776540&siteId=291194637