LeetCode Q 1105 - Filling Bookcase Shelves
We have a sequence of books: the i-th
book has thickness books[i][0]
and height books[i][1]
.
We want to place these books in order onto bookcase shelves that have total width shelf_width
.
We choose some of the books to place on this shelf (such that the sum of their thickness is <= shelf_width), then build another level of 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 again 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.
Constraints:
1 <= books.length <= 1000
1 <= books[i][0] <= shelf_width <= 1000
1 <= books[i][1] <= 1000
Solution
Solution 1: DP
Code:
public int minHeightShelves(int[][] books, int shelf_width) {
int[] dp = new int[books.length + 1];
for (int i = 1; i <= books.length; i++) {
dp[i] = dp[i - 1] + books[i - 1][1];
int width = books[i - 1][0];
int height = books[i - 1][1];
for (int j = i - 1; j > 1; j++) {
width += books[j - 1][0];
if (width > shelf_width) break;
height = Math.max(height, books[j - 1][1]);
dp[i] = Math.min(dp[i], dp[j - 1] + height);
}
}
return dp[books.length];
}
Solution 2: DFS + memorization
Code:
int[][] memo;
public int minHeightShelves(int[][] books, int shelf_width) {
memo = new int[books.length][shelf_width + 1];
return dfs(books, 0, shelf_width, shelf_width, 0);
}
private int dfs(int[][] books, int curr, int left_width, int shelf_width, int curHeight) {
if (curr == books.length) return curHeight;
if (memo[curr][left_width] != 0) return memo[curr][left_width];
memo[curr][left_width] = curHeight +
dfs(books, curr + 1, shelf_width - books[curr][0], shelf_width, books[curr][1]);
if (left_width - books[curr][0] >= 0)
memo[curr][left_width] = Math.min(memo[curr][left_width],
dfs(books, curr + 1, left_width - books[curr][0],
shelf_width, Math.max(curHeight, books[curr][1])));
return memo[curr][left_width];
}