背包問題

0-1背包和完全背包的逆序和正序
lintcode背包問題匯總
LeetCode動(dòng)態(tài)規(guī)劃刷題記錄(一)背包問題
ACWing中有足夠的背包問題

  • 92. Backpack
    0-1背包毁腿,單次選擇晴弃,最大體積
    Given n items with size Ai, an integer m denotes the size of a backpack. How full you can fill this backpack?
//time: O(nm)   space: O(nm) 
public class Solution {
    /**
     * @param m: An integer m denotes the size of a backpack
     * @param A: Given n items with size A[i]
     * @return: The maximum size
     */
    public int backPack(int m, int[] A) {
        // write your code here
        int n = A.length;
        int[][] dp = new int[n + 1][m + 1];
        for (int i = 1; i <= n; i++) {
            for (int j = 0; j <= m; j++) {
                if (j < A[i-1]) {
                    dp[i][j] = dp[i-1][j];
                } else {
                    dp[i][j] = Math.max(dp[i-1][j], dp[i-1][j-A[i-1]] + A[i-1]);
                }
            }
        }
        return dp[n][m];
    }
}
//time: O(nm)   space: O(nm) 
//注意點(diǎn)1:第i行的狀態(tài)只與i-1行的狀態(tài)有關(guān),可以用兩個(gè)一維數(shù)組pre[] and cur[]
//注意點(diǎn)2:第j列的狀態(tài)只與當(dāng)前列和之前列有關(guān)缤骨,可以從后向前逆序更新
public class Solution {
    /**
     * @param m: An integer m denotes the size of a backpack
     * @param A: Given n items with size A[i]
     * @return: The maximum size
     */
    public int backPack(int m, int[] A) {
        // write your code here
        int n = A.length;
        int[] dp = new int[m + 1];
        for (int i = 1; i <= n; i++) {
            for (int j = m; j >= A[i-1]; j--) {
                dp[j] = Math.max(dp[j], dp[j-A[i-1]] + A[i-1]);
            }
        }
        return dp[m];
    }
}
  • 125. Backpack II
    0-1 背包,單次選擇尺借,最大價(jià)值
    There are n items and a backpack with size m. Given array A representing the size of each item and array V representing the value of each item. What's the maximum value can you put into the backpack?
//time: O(nm)   space: O(nm)
public class Solution {
    /**
     * @param m: An integer m denotes the size of a backpack
     * @param A: Given n items with size A[i]
     * @param V: Given n items with value V[i]
     * @return: The maximum value
     */
    public int backPackII(int m, int[] A, int[] V) {
        // write your code here
        int n = A.length;
        int[][] dp = new int[n + 1][m + 1];
        //dp[i][j] means the max value when we have considered the first i items with size j
        for (int i = 1; i <= n; i++) {
            for (int j = 0; j <= m; j++) {
                if (j < A[i-1]) {       
                    //don't consider the item
                    dp[i][j] = dp[i-1][j];    
                } else {
                    //consider it, add/not add it can we have more values 
                    dp[i][j] = Math.max(dp[i-1][j], dp[i-1][j-A[i-1]] + V[i-1]);
                }
            }
        }
        return dp[n][m];
    }
}
//time: O(nm)   space: O(m)
public class Solution {
    /**
     * @param m: An integer m denotes the size of a backpack
     * @param A: Given n items with size A[i]
     * @param V: Given n items with value V[i]
     * @return: The maximum value
     */
    public int backPackII(int m, int[] A, int[] V) {
        // write your code here
        int n = A.length;
        int[] dp = new int[m + 1];
        //dp[i][j] means the max value when we have considered the first i items with size j
        for (int i = 1; i <= n; i++) {
            for (int j = m; j >= A[i-1]; j--) {
                dp[j] = Math.max(dp[j], dp[j-A[i-1]] + V[i-1]);
            }
        }
        return dp[m];
    }
}
  • 背包3
    完全背包绊起,重復(fù)選擇,最大價(jià)值
    Given n kind of items with size Ai and value Vi( each item has an infinite number available) and a backpack with size m. What's the maximum value can you put into the backpack?
//time: O(nm)   space: O(nm)
public class solution {
    public int backpackIII(int[] A, int[] V, int m) {
        int n = A.length;
        int[][] dp = new int[n + 1][m + 1];
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
                //注意后者是dp[i][xxx] 不是 dp[i-1][xxx]
                if (j >= A[i-1])
                    dp[i][j] = Math.max(dp[i-1][j], dp[i][j-A[i-1]] + V[i-1]);
            }
        }
        return dp[n][m];
    } 
}
//time: O(nm)   space: O(m)
public class solution {
    public int backpackIII(int[] A, int[] V, int m) {
        int n = A.length;
        int[] dp = new int[m + 1];
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
                if (j >= A[i-1])
                    dp[j] = Math.max(dp[j], dp[j-A[i-1]] + V[i-1]);
            }
        }
        return dp[m];
    } 
}
  • 562. Backpack IV
    完全背包燎斩,重復(fù)選擇虱歪,最多裝滿可能性
    Given an integer array nums[] which contains n unique positive numbers, num[i] indicate the size of ith item. An integer target denotes the size of backpack. Find the number of ways to fill the backpack. Each item may be chosen unlimited number of times.
public class Solution {
    /**
     * @param nums: an integer array and all positive numbers, no duplicates
     * @param target: An integer
     * @return: An integer
     */
    public int backPackIV(int[] nums, int target) {
        // write your code here
        int n = nums.length;
        int[][] dp = new int[n + 1][target + 1];
        for (int i = 0; i <= n; i++) {
            dp[i][0] = 1;                                //有前i個(gè)item蜂绎,得到weight為0的方式為1
        }
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= target; j++) {
                if (j < nums[i-1]) {
                    dp[i][j] = dp[i-1][j];
                } else {
                    dp[i][j] = dp[i-1][j] + dp[i][j - nums[i-1]];
                }
            }
        }
        return dp[n][target];
    }
}
public class Solution {
    /**
     * @param nums: an integer array and all positive numbers, no duplicates
     * @param target: An integer
     * @return: An integer
     */
    public int backPackIV(int[] nums, int target) {
        // write your code here
        int n = nums.length;
        int[] dp = new int[target + 1];
        dp[0] = 1;
        for (int i = 0; i < n; i++) {
            for (int j = 1; j <= target; j++) {
                if (nums[i] == j) dp[j] += 1;
                else if (nums[i] < j) dp[j] += dp[j - nums[i]];
            }
        }
        return dp[target];
    }
}
  • 563. Backpack V
    0-1背包,單次選擇笋鄙,最多裝滿可能性
    Given n items with size nums[i] which an integer array and all positive numbers. An integer target denotes the size of a backpack. Find the number of possible fill the backpack. Each item may only be used once
public class Solution {
    /**
     * @param nums: an integer array and all positive numbers
     * @param target: An integer
     * @return: An integer
     */
    public int backPackV(int[] nums, int target) {
        // write your code here
        int n = nums.length;
        int[][] dp = new int[n + 1][target + 1];
        for (int i = 0; i <= n; i++) {
            dp[i][0] = 1;
        }
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= target; j++) {
                if (j < nums[i-1]) {
                    dp[i][j] = dp[i-1][j];
                } else {
                    dp[i][j] = dp[i-1][j] + dp[i-1][j - nums[i-1]];
                }
            }
        }
        return dp[n][target];
    }
}
public class Solution {
    /**
     * @param nums: an integer array and all positive numbers
     * @param target: An integer
     * @return: An integer
     */
    public int backPackV(int[] nums, int target) {
        // write your code here
        int n = nums.length;
        int[] dp = new int[target + 1];
        dp[0] = 1;
        for (int i = 0; i < n; i++) {
            for (int j = target; j >= nums[i]; j--) {
                dp[j] += dp[j - nums[i]];
            }
        }
        return dp[target];
    }
}
  • 多重背包
    有 N 種物品和一個(gè)容量是 V 的背包师枣。
    第 i 種物品最多有 si 件,每件體積是 vi萧落,價(jià)值是 wi践美。
    求解將哪些物品裝入背包,可使物品體積總和不超過背包容量铐尚,且價(jià)值總和最大拨脉。
    輸出最大價(jià)值。
//基礎(chǔ)解答
import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in); 
        int N = in.nextInt();
        int V = in.nextInt();
        int[] v = new int[N + 1];
        int[] w = new int[N + 1];
        int[] s = new int[N + 1];
        for (int i = 1; i <= N; i++) {
            v[i] = in.nextInt();
            w[i] = in.nextInt();
            s[i] = in.nextInt();
        }
        in.close();
        
        //核心代碼  
        int[] dp = new int[V + 1];
        for (int i = 1; i <= N; i++) {
            for (int j = V; j >= 0; j--) {              //j和k的兩個(gè)循環(huán)互換位置出錯(cuò)宣增,為什么
                for (int k = 0; k <= s[i]; k++) {           
                    if (j >= k*v[i])
                        dp[j] = Math.max(dp[j], dp[j - k*v[i]] + k*w[i]);
                }
            }
        }
        System.out.println(dp[V]);
    }
}
//二進(jìn)制優(yōu)化
//單調(diào)隊(duì)列優(yōu)化
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末玫膀,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子爹脾,更是在濱河造成了極大的恐慌帖旨,老刑警劉巖,帶你破解...
    沈念sama閱讀 212,718評(píng)論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件灵妨,死亡現(xiàn)場離奇詭異解阅,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)泌霍,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,683評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門货抄,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人朱转,你說我怎么就攤上這事蟹地。” “怎么了藤为?”我有些...
    開封第一講書人閱讀 158,207評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵怪与,是天一觀的道長。 經(jīng)常有香客問我缅疟,道長分别,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 56,755評(píng)論 1 284
  • 正文 為了忘掉前任存淫,我火速辦了婚禮耘斩,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘桅咆。我一直安慰自己煌往,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,862評(píng)論 6 386
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著刽脖,像睡著了一般羞海。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上曲管,一...
    開封第一講書人閱讀 50,050評(píng)論 1 291
  • 那天却邓,我揣著相機(jī)與錄音,去河邊找鬼院水。 笑死腊徙,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的檬某。 我是一名探鬼主播撬腾,決...
    沈念sama閱讀 39,136評(píng)論 3 410
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢(mèng)啊……” “哼恢恼!你這毒婦竟也來了民傻?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,882評(píng)論 0 268
  • 序言:老撾萬榮一對(duì)情侶失蹤场斑,失蹤者是張志新(化名)和其女友劉穎漓踢,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體漏隐,經(jīng)...
    沈念sama閱讀 44,330評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡喧半,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,651評(píng)論 2 327
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了青责。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片挺据。...
    茶點(diǎn)故事閱讀 38,789評(píng)論 1 341
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖脖隶,靈堂內(nèi)的尸體忽然破棺而出扁耐,到底是詐尸還是另有隱情,我是刑警寧澤浩村,帶...
    沈念sama閱讀 34,477評(píng)論 4 333
  • 正文 年R本政府宣布,位于F島的核電站占哟,受9級(jí)特大地震影響心墅,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜榨乎,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 40,135評(píng)論 3 317
  • 文/蒙蒙 一怎燥、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧蜜暑,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,864評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至依许,卻和暖如春膘婶,著一層夾襖步出監(jiān)牢的瞬間悬襟,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,099評(píng)論 1 267
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留棺牧,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 46,598評(píng)論 2 362
  • 正文 我出身青樓醉锄,卻偏偏與公主長得像檩小,于是被迫代替她去往敵國和親规求。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,697評(píng)論 2 351

推薦閱讀更多精彩內(nèi)容