LeetCode(354):俄罗斯套娃信封问题 Russian Doll Envelopes(Java)

2020.1.10 . LeetCode 从零单刷个人笔记整理(持续更新)

github:https://github.com/ChopinXBP/LeetCode-Babel

这道题是之前 LeetCode(300):最长上升子序列 Longest Increasing Subsequence(Java) 的拓展问题。对所有信封排序之后,原题相当于是二维的最长上升子序列。

思路主要有动态规划和动态规划+二分查找。

普通的动态规划相当于是一个01背包问题。建立dp数组,dp[i]代表包括第i+1封信,当前信封的最大嵌套数量。

每次第i封信的最大嵌套数量需要遍历信件j=[0,i]保留最大值,动态转移方程为:

dp[i] = Math.max(dp[i], dp[j] + 1);

由于最大嵌套数量的信封不一定包括最后一封,因此需要全程取最大值。

动态规划+二分查找的思路与最长上升子序列中的思路类似。


传送门:俄罗斯套娃信封问题

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)

Note: Rotation is not allowed.

给定一些标记了宽度和高度的信封,宽度和高度以整数对形式 (w, h) 出现。当另一个信封的宽度和高度都比这个信封大的时候,这个信封就可以放进另一个信封里,如同俄罗斯套娃一样。

请计算最多能有多少个信封能组成一组“俄罗斯套娃”信封(即可以把一个信封放到另一个信封里面)。

说明: 不允许旋转信封。

示例:
输入: envelopes = [[5,4],[6,4],[6,7],[2,3]]
输出: 3 
解释: 最多信封的个数为 3, 组合为: [2,3] => [5,4] => [6,7]。


import java.util.Arrays;

/**
 *
 * 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)
 * Note: Rotation is not allowed.
 * 给定一些标记了宽度和高度的信封,宽度和高度以整数对形式 (w, h) 出现。当另一个信封的宽度和高度都比这个信封大的时候,这个信封就可以放进另一个信封里,如同俄罗斯套娃一样。
 * 请计算最多能有多少个信封能组成一组“俄罗斯套娃”信封(即可以把一个信封放到另一个信封里面)。
 * 说明: 不允许旋转信封。
 *
 */

public class RussianDollEnvelopes {
   
    //动态规划
    public int maxEnvelopes(int[][] envelopes) {
   
        Arrays.s
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值