原文:

给定 n 个物品的重量和值,将这些物品放入容量为 w 的背包中,得到背包中的最大总值。换句话说,给定两个整数数组,val[0..n-1]和 wt[0..n-1]分别表示与 n 个项目相关联的值和权重。同样给定一个代表背包容量的整数 w,找出项目,使得给定子集的这些项目的权重之和小于或等于 w。您不能分解一个项目,要么选择完整的项目,要么不选择它(0-1 属性)。 先决条件: 示例:

input : val[] = {60, 100, 120};
        wt[] = {10, 20, 30};
        w = 50;
output : 220 //maximum value that can be obtained
         30 20 //weights 20 and 30 are included. 
input : val[] = {40, 100, 50, 60};
        wt[] = {20, 10, 40, 30};
        w = 60;
output : 200
         30 20 10

进场: 让 val[] = {1,4,5,7},wt[] = {1,3,4,5} w = 7。 2d 背包表看起来像:

从 k[n][w]开始回溯。这里 k[n][w]是 9。 由于该值来自顶部(灰色箭头所示),因此不包括该行中的项目。在桌子上垂直向上,不要把这个放在背包里。现在,这个值 k[n-1][w]是 9,它不是从顶部来的,这意味着这一行中的项目被包括在内,并垂直向上,然后按所包括项目的重量向左移动(如黑色箭头所示)。继续这个过程,在背包中包括总价值为 9 的权重 3 和 4。

c

// cpp code for dynamic programming based
// solution for 0-1 knapsack problem
#include 
#include 
using namespace std;
// a utility function that returns maximum of two integers
int max(int a, int b) { return (a > b) ? a : b; }
// prints the items which are put in a knapsack of capacity w
void printknapsack(int w, int wt[], int val[], int n)
{
    int i, w;
    int k[n   1][w   1];
    // build table k[][] in bottom up manner
    for (i = 0; i <= n; i  ) {
        for (w = 0; w <= w; w  ) {
            if (i == 0 || w == 0)
                k[i][w] = 0;
            else if (wt[i - 1] <= w)
                k[i][w] = max(val[i - 1]  
                    k[i - 1][w - wt[i - 1]], k[i - 1][w]);
            else
                k[i][w] = k[i - 1][w];
        }
    }
    // stores the result of knapsack
    int res = k[n][w];
    cout<< res << endl;
    w = w;
    for (i = n; i > 0 && res > 0; i--) {
        // either the result comes from the top
        // (k[i-1][w]) or from (val[i-1]   k[i-1]
        // [w-wt[i-1]]) as in knapsack table. if
        // it comes from the latter one/ it means
        // the item is included.
        if (res == k[i - 1][w])
            continue;   
        else {
            // this item is included.
            cout<<" "<

c

// cpp code for dynamic programming based
// solution for 0-1 knapsack problem
#include 
// a utility function that returns maximum of two integers
int max(int a, int b) { return (a > b) ? a : b; }
// prints the items which are put in a knapsack of capacity w
void printknapsack(int w, int wt[], int val[], int n)
{
    int i, w;
    int k[n   1][w   1];
    // build table k[][] in bottom up manner
    for (i = 0; i <= n; i  ) {
        for (w = 0; w <= w; w  ) {
            if (i == 0 || w == 0)
                k[i][w] = 0;
            else if (wt[i - 1] <= w)
                k[i][w] = max(val[i - 1]  
                    k[i - 1][w - wt[i - 1]], k[i - 1][w]);
            else
                k[i][w] = k[i - 1][w];
        }
    }
    // stores the result of knapsack
    int res = k[n][w];   
    printf("%d\n", res);
    w = w;
    for (i = n; i > 0 && res > 0; i--) {
        // either the result comes from the top
        // (k[i-1][w]) or from (val[i-1]   k[i-1]
        // [w-wt[i-1]]) as in knapsack table. if
        // it comes from the latter one/ it means
        // the item is included.
        if (res == k[i - 1][w])
            continue;       
        else {
            // this item is included.
            printf("%d ", wt[i - 1]);
            // since this weight is included its
            // value is deducted
            res = res - val[i - 1];
            w = w - wt[i - 1];
        }
    }
}
// driver code
int main()
{
    int val[] = { 60, 100, 120 };
    int wt[] = { 10, 20, 30 };
    int w = 50;
    int n = sizeof(val) / sizeof(val[0]);
    printknapsack(w, wt, val, n);
    return 0;
}

java 语言(一种计算机语言,尤用于创建网站)

// java code for dynamic programming based
// solution for 0-1 knapsack problem
class gfg {
    // a utility function that returns
    // maximum of two integers
    static int max(int a, int b)
    {
        return (a > b) ? a : b;
    }
    // prints the items which are put
    // in a knapsack of capacity w
    static void printknapsack(int w, int wt[],
                             int val[], int n)
    {
        int i, w;
        int k[][] = new int[n   1][w   1];
        // build table k[][] in bottom up manner
        for (i = 0; i <= n; i  ) {
            for (w = 0; w <= w; w  ) {
                if (i == 0 || w == 0)
                    k[i][w] = 0;
                else if (wt[i - 1] <= w)
                    k[i][w] = math.max(val[i - 1]  
                              k[i - 1][w - wt[i - 1]], k[i - 1][w]);
                else
                    k[i][w] = k[i - 1][w];
            }
        }
        // stores the result of knapsack
        int res = k[n][w];
        system.out.println(res);
        w = w;
        for (i = n; i > 0 && res > 0; i--) {
            // either the result comes from the top
            // (k[i-1][w]) or from (val[i-1]   k[i-1]
            // [w-wt[i-1]]) as in knapsack table. if
            // it comes from the latter one/ it means
            // the item is included.
            if (res == k[i - 1][w])
                continue;
            else {
                // this item is included.
                system.out.print(wt[i - 1]   " ");
                // since this weight is included its
                // value is deducted
                res = res - val[i - 1];
                w = w - wt[i - 1];
            }
        }
    }
    // driver code
    public static void main(string arg[])
    {
        int val[] = { 60, 100, 120 };
        int wt[] = { 10, 20, 30 };
        int w = 50;
        int n = val.length;
        printknapsack(w, wt, val, n);
    }
}
// this code is contributed by anant agarwal.

python 3

# python3 code for dynamic programming
# based solution for 0-1 knapsack problem
# prints the items which are put in a
# knapsack of capacity w
def printknapsack(w, wt, val, n):
    k = [[0 for w in range(w   1)]
            for i in range(n   1)]
    # build table k[][] in bottom
    # up manner
    for i in range(n   1):
        for w in range(w   1):
            if i == 0 or w == 0:
                k[i][w] = 0
            elif wt[i - 1] <= w:
                k[i][w] = max(val[i - 1]
                    k[i - 1][w - wt[i - 1]],
                               k[i - 1][w])
            else:
                k[i][w] = k[i - 1][w]
    # stores the result of knapsack
    res = k[n][w]
    print(res)
    w = w
    for i in range(n, 0, -1):
        if res <= 0:
            break
        # either the result comes from the
        # top (k[i-1][w]) or from (val[i-1]
        #   k[i-1] [w-wt[i-1]]) as in knapsack
        # table. if it comes from the latter
        # one/ it means the item is included.
        if res == k[i - 1][w]:
            continue
        else:
            # this item is included.
            print(wt[i - 1])
            # since this weight is included
            # its value is deducted
            res = res - val[i - 1]
            w = w - wt[i - 1]
# driver code
val = [ 60, 100, 120 ]
wt = [ 10, 20, 30 ]
w = 50
n = len(val)
printknapsack(w, wt, val, n)
# this code is contributed by aryan garg.

c

// c# code for dynamic programming based
// solution for 0-1 knapsack problem
using system ;
class gfg {
    // a utility function that returns
    // maximum of two integers
    static int max(int a, int b)
    {
        return (a > b) ? a : b;
    }
    // prints the items which are put
    // in a knapsack of capacity w
    static void printknapsack(int w, int []wt,
                            int []val, int n)
    {
        int i, w;
        int [,]k = new int[n   1,w   1];
        // build table k[][] in bottom up manner
        for (i = 0; i <= n; i  ) {
            for (w = 0; w <= w; w  ) {
                if (i == 0 || w == 0)
                    k[i,w] = 0;
                else if (wt[i - 1] <= w)
                    k[i,w] = math.max(val[i - 1]  
                            k[i - 1,w - wt[i - 1]], k[i - 1,w]);
                else
                    k[i,w] = k[i - 1,w];
            }
        }
        // stores the result of knapsack
        int res = k[n,w];
        console.writeline(res);
        w = w;
        for (i = n; i > 0 && res > 0; i--) {
            // either the result comes from the top
            // (k[i-1][w]) or from (val[i-1]   k[i-1]
            // [w-wt[i-1]]) as in knapsack table. if
            // it comes from the latter one/ it means
            // the item is included.
            if (res == k[i - 1,w])
                continue;
            else {
                // this item is included.
                console.write(wt[i - 1]   " ");
                // since this weight is included its
                // value is deducted
                res = res - val[i - 1];
                w = w - wt[i - 1];
            }
        }
    }
    // driver code
    public static void main()
    {
        int []val = { 60, 100, 120 };
        int []wt = { 10, 20, 30 };
        int w = 50;
        int n = val.length;
        printknapsack(w, wt, val, n);
    }
}
// this code is contributed by ryuga.

服务器端编程语言(professional hypertext preprocessor 的缩写)

 0 && $res > 0; $i--)
    {
        // either the result comes from the top
        // (k[i-1][w]) or from (val[i-1]   k[i-1]
        // [w-wt[i-1]]) as in knapsack table. if
        // it comes from the latter one/ it means
        // the item is included.
        if ($res == $k[$i - 1][$w])
            continue;    
        else
        {
            // this item is included.
            echo $wt[$i - 1] . " ";
            // since this weight is included
            // its value is deducted
            $res = $res - $val[$i - 1];
            $w = $w - $wt[$i - 1];
        }
    }
}
// driver code
$val = array(60, 100, 120);
$wt = array(10, 20, 30);
$w = 50;
$n = sizeof($val);
printknapsack($w, $wt, $val, $n);
// this code is contributed by ita_c
?>

java 描述语言


output: 

220
30 20