1105. Filling Bookcase Shelves
- Filling Bookcase Shelves python solution
题目描述
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.
解析
题目的意思是,每层书架的宽度是固定的,但是高度可调解的。
摆放书的顺序与我们放书的顺序相同,这就意味着我们不可以调价书的顺序,只能按照序号一本一本的摆放。例如5号书不能被放在第2层,即使6号书的宽度可以被放在第二层,他依然不可以被放置在第二层。6号书只能在5号书的右边或者下一层。这条限制大大简化了解体的难度!
其实题目解读到这里,大家应该可以判断出这是一道动态规划题。
对于每一个新来的书,他只有两个选择:
- 如果当前层宽度允许,将这本书放在当前层
- 如果当前层宽度不允许,只能将该书放在下一层
所以我们只需要动态更新当前结果即可。
求摆放前i本书需要的最小高度,首先需要求摆放前i-1书需要的最小高度
建立数组dp[i]用来储存第i本书的最小高度,动态更新。
class Solution:
def minHeightShelves(self, books: List[List[int]], shelf_width: int) -> int:
n=len(books)
dp=[float('inf')]*(n+1)
dp[0]=0
for i in range (1,n+1):
max_width=shelf_width
max_height=0
j=i-1
while j>=0 and max_width-books[j][0]>=0:
max_width-=books[j][0]
max_height=max(max_height,books[j][1])
dp[i]=min(dp[i],dp[j]+max_height)
j-=1
return dp[n]
Reference
https://leetcode.com/problems/filling-bookcase-shelves/discuss/323415/simple-Python-DP-solution