TypechoJoeTheme

IT技术分享

统计

[LintCode 125] Backpack II [Java]

2017-10-13
/
0 评论
/
698 阅读
/
正在检测是否收录...
10/13

1. Description

Given n items with size Ai and value Vi, and a backpack with size m. What's the maximum value can you put into the backpack?

Notice

You cannot divide item into small pieces
the total size of items you choose should smaller or equal to m.

2. Example

Given 4 items with size [2, 3, 5, 7] and value [1, 5, 2, 4], and a backpack with size 10.
The maximum value is 9.

3. Code

public class LintCode0125 {
    public int backPackII(int m, int[] A, int[] V) {
        if (m < 0 || A == null || A.length == 0 ||
            V == null || V.length == 0 || A.length != V.length) {
            return 0;
        }

        int[][] dp = new int[A.length + 1][m + 1];

        for (int i = 0; i < A.length; i++) {
            for (int j = 0; j <= m; j++) {
                dp[i + 1][j] = dp[i][j];
                if (j >= A[i]) {
                    dp[i + 1][j] = Math.max(dp[i][j], dp[i][j - A[i]] + V[i]);
                }
            }
        }

        return dp[A.length][m];
    }

    public static void main(String[] args) {
        LintCode0125 lintcode = new LintCode0125();
        int[] A = new int[] { 2, 3, 5, 7 };
        int[] V = new int[] { 1, 5, 2, 4 };
        System.out.println(lintcode.backPackII(10, A, V));
    }
}
DP
朗读
赞 · 0
版权属于:

IT技术分享

本文链接:

https://idunso.com/archives/1007/(转载时请注明本文出处及文章链接)