You are given a 2D array of integers envelopes where envelopes[i] = [wi, hi] represents the width and the height of an envelope.
One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope’s width and height.
Return the maximum number of envelopes you can Russian doll (i.e., put one inside the other).
Note: You cannot rotate an envelope.
Example 1:
Input: envelopes = [[5,4],[6,4],[6,7],[2,3]]
Output: 3
Explanation: The maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]).
Example 2:
Input: envelopes = [[1,1],[1,1],[1,1]]
Output: 1
Constraints:
- 1 <= envelopes.length <= 105
- envelopes[i].length == 2
- 1 <= wi, hi <= 105
- 按照 width 递增排序, 如果 widht 相同则按 height 递减排序
- 找到 height 的 LIS(longest increasing subsequence)
impl Solution {
pub fn max_envelopes(mut envelopes: Vec<Vec<i32>>) -> i32 {
envelopes.sort_by(|p1, p2| {
if p1[0] == p2[0] {
return p2[1].cmp(&p1[1]);
}
p1[0].cmp(&p2[0])
});
let mut sub = Vec::new();
for envelope in envelopes {
if let Some(last) = sub.last() {
if &envelope[1] > last {
sub.push(envelope[1]);
continue;
}
let i = sub.iter().position(|v| v >= &envelope[1]).unwrap();
sub[i] = envelope[1];
continue;
}
sub.push(envelope[1]);
}
sub.len() as i32
}
}

本文探讨了俄罗斯套娃信封问题的解决方案,即给定一系列不同尺寸的信封,如何找出能彼此套叠的最大数量。通过特定排序及最长递增子序列算法(LIS),文章详细介绍了实现这一目标的方法。
521

被折叠的 条评论
为什么被折叠?



