[LeetCode] Filling Bookcase Shelves

1105. Filling Bookcase Shelves

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
//width, bookid
int dp[1001][1001];
int helper(vector<vector<int>>& b, int &W, int id, int cw, int ch) {
if(id == b.size()) return ch;
if(dp[id][cw] != -1) return dp[id][cw];
dp[id][cw] = INT_MAX;
if(cw + b[id][0] <= W) { //put beside if possible
dp[id][cw] = helper(b,W,id + 1, cw + b[id][0], max(ch, b[id][1]));
}
dp[id][cw] = min(dp[id][cw], helper(b,W,id+1,b[id][0], b[id][1]) + ch);
return dp[id][cw];
}
public:
int minHeightShelves(vector<vector<int>>& books, int shelfWidth) {
memset(dp, -1, sizeof(dp));
return helper(books, shelfWidth, 0, 0, 0);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/25/PS/LeetCode/filling-bookcase-shelves/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.