Description
You are given an array books where books[i] = [thicknessi, heighti] indicates the thickness and height of the ith book. You are also given an integer shelfWidth.
We want to place these books in order onto bookcase shelves that have a total width shelfWidth.
We choose some of the books to place on this shelf such that the sum of their thickness is less than or equal to shelfWidth, then build another level of the shelf of the bookcase so that the total height of the bookcase has increased by the maximum height of the books we just put down. We repeat this process until there are no more books to place.
Note that at each step of the above process, the order of the books we place is the same order as the given sequence of books.
For example, if we have an ordered list of 5 books, we might place the first and second book onto the first shelf, the third book on the second shelf, and the fourth and fifth book on the last shelf.
Return the minimum possible height that the total bookshelf can be after placing shelves in this manner.
Examples
Example 1:
Example 2:
Constraints:
思路
首先这个问题肯定是dp,问题是怎么dp,我不太能解释最后用的dp方法,就添加了一些相关注释,希望下次看的时候还能看懂吧!
代码
class Solution {
public int minHeightShelves(int[][] books, int shelf_width) {
int[] dp = new int[books.length + 1];
// 一本书都不放,height = 0
dp[0] = 0;
// 从放第一本书开始循环
for (int i = 1; i <= books.length; i++) {
// 第i本书的属性
int width = books[i - 1][0];
int height = books[i - 1][1];
// 直接放到下一层
dp[i] = dp[i - 1] + height;
// 往前回溯,就认为当前这本书新开一行,从之前的书里面抽东西放到这一行里面来
// 因为有0本书height=0兜底,所以可以这么执行
for (int j = i - 1; j > 0 && width + books[j - 1][0] <= shelf_width; j--) {
// 已知书i在这一行,这一行还可以在左侧放多少书 (最多能放shelf_width)
height = Math.max(height, books[j - 1][1]);
width += books[j - 1][0];
dp[i] = Math.min(dp[i], dp[j - 1] + height);
}
}
return dp[books.length];
}
}