1105. Filling Bookcase Shelves解題報(bào)告

Description:

image.png

Example:

image.png

Link:

https://leetcode.com/problems/filling-bookcase-shelves/

解題方法:

DP:
dp[i] represents the minimum height of total shelves we build that ended by books[i].
For a given book with index i, assume this book is the last book in current level, then we can try to add other books with index < i into our current level, unless the total width of current level is bigger than the limit shelf_width. During this process, we will find out the minimum height of total shelves we've build, which is the dp[i] we are trying to figure out for current book.

dp[i]代表以當(dāng)前這本書為本層書架最后一本書的時(shí)候,目前我們建的書架的最小高度。
當(dāng)我們計(jì)算到書本i的時(shí)候,假設(shè)這本書是當(dāng)前l(fā)evel最后一本書,那么我們可以嘗試把之前的書本加入到本層書架來,只要這些書本的寬度不超過規(guī)定的寬度,在這個(gè)過程中。我們會(huì)找到以當(dāng)前這本書為本層書架最后一本書為前提條件的時(shí)候,我們目前建立的書架最小的高度。然后把它更新到dp數(shù)組中。最后一個(gè)值就是我們的答案。

Time Complexity:

O(n^2)

完整代碼:

class Solution {
public:
    int minHeightShelves(vector<vector<int>>& books, int shelf_width) {
        vector<int> dp;
        int size = books.size();
        if(!size)
            return 0;
        dp.push_back(books[0][1]);
        for(int i = 1; i < size; i++) {
            int currWidth = books[i][0];
            int maxHeight = books[i][1];
            int minDp = maxHeight + dp.back();
            for(int j = dp.size() - 1; j >= 0; j--) {
                currWidth += books[j][0];
                if(currWidth > shelf_width)
                    break;
                maxHeight = max(maxHeight, books[j][1]);
                if(j == 0)
                    minDp = min(maxHeight, minDp);
                else
                    minDp = min(maxHeight + dp[j - 1], minDp);
            }
            dp.push_back(minDp);
        }
        return dp.back();
    }
};
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,847評(píng)論 0 10
  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 11,067評(píng)論 0 23
  • 雅思口語考試是考生與考官面對(duì)面進(jìn)行口語交流,在考試中若是考生做了一些不該做的事情,比如手勢(shì)不對(duì)等等,都會(huì)給考官留下...
    春喜外語學(xué)堂閱讀 307評(píng)論 0 0
  • 昨晚寫文章《時(shí)常感恩》,發(fā)到日更群發(fā)現(xiàn)有幾位群友都在寫感恩分享,原來是有計(jì)劃性的再寫感恩主題文章。 時(shí)懷感恩心,確...
    戀上火烈鳥閱讀 424評(píng)論 0 3
  • 我是一個(gè)平凡的人 知乎上有個(gè)帖子問:“你是在什么時(shí)候發(fā)現(xiàn)自己是個(gè)平凡人的?” 有人說,當(dāng)別人答一份試題要20分鐘而...
    飯飯的讀書筆記閱讀 432評(píng)論 0 0

友情鏈接更多精彩內(nèi)容