JavaInterview JavaInterview
首页
指南
分类
标签
归档
  • CSDN (opens new window)
  • 文档集合 (opens new window)
  • 系统架构 (opens new window)
  • 微信号 (opens new window)
  • 公众号 (opens new window)

『Java面试+Java学习』
首页
指南
分类
标签
归档
  • CSDN (opens new window)
  • 文档集合 (opens new window)
  • 系统架构 (opens new window)
  • 微信号 (opens new window)
  • 公众号 (opens new window)
  • 指南
  • 简历

  • Java

  • 面试

  • 算法

  • algorithm
  • leetcode
JavaInterview.cn
2022-11-27
目录

填充书架Java

文章发布较早,内容可能过时,阅读注意甄别。

# 题目

给定一个数组 books ,其中 books[i] = [thicknessi, heighti] 表示第 i 本书的厚度和高度。你也会得到一个整数 shelfWidth 。

按顺序 将这些书摆放到总宽度为 shelfWidth 的书架上。

先选几本书放在书架上(它们的厚度之和小于等于书架的宽度 shelfWidth ),然后再建一层书架。重复这个过程,直到把所有的书都放在书架上。

需要注意的是,在上述过程的每个步骤中,摆放书的顺序与你整理好的顺序相同。

  • 例如,如果这里有 5 本书,那么可能的一种摆放情况是:第一和第二本书放在第一层书架上,第三本书放在第二层书架上,第四和第五本书放在最后一层书架上。

每一层所摆放的书的最大高度就是这一层书架的层高,书架整体的高度为各层高之和。

以这种方式布置书架,返回书架整体可能的最小高度。

示例 1:

输入:books = [[1,1],[2,3],[2,3],[1,1],[1,1],[1,1],[1,2]], shelf_width = 4
输出:6
解释:
3 层书架的高度和为 1 + 3 + 2 = 6 。
第 2 本书不必放在第一层书架上。

示例 2:

输入: books = [[1,3],[2,4],[3,2]], shelfWidth = 6
输出: 4   

提示:

  • 1 <= books.length <= 1000
  • 1 <= thicknessi <= shelfWidth <= 1000
  • 1 <= heighti <= 1000

# 思路

枚举了所有可能的放置方法

dfs

# 解法


class Solution {
    // 填充书架
    public int minHeightShelves(int[][] books, int shelf_width) {

        /*
        整体思路就是暴力枚举每层书架书的不同放法
         */
        int[] cache = new int[books.length];
        Arrays.fill(cache, -1);
        return dfs(books, 0, shelf_width, cache);
    }

    private int dfs(int[][] books, int index, int width, int[] cache) {
        if (index >= books.length) return 0;
        if (cache[index] != -1) return cache[index];
        int curWidth = 0;
        int maxHeight = 0;
        int ans = Integer.MAX_VALUE;
        for (int i = index; i < books.length; i++) {
            curWidth += books[i][0];
            maxHeight = Math.max(maxHeight, books[i][1]);
            if (curWidth > width) break;
            ans = Math.min(ans, maxHeight + dfs(books, i + 1, width, cache));
        }
        return cache[index] = ans;}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

# 总结

  • 分析出几种情况,然后分别对各个情况实现
微信 支付宝
最近更新
01
1601. 最多可达成的换楼请求数目 Java
06-09
02
1625. 执行操作后字典序最小的字符串 Java
06-09
03
1626. 无矛盾的最佳球队 Java
06-09
更多文章>
Theme by Vdoing | Copyright © 2019-2025 JavaInterview.cn
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式