Page tree

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
languagepy
title0-1 Knapsack Problem
linenumberstrue
collapsetrue

##########################################
## 상향식(타뷸레이션): 미리 값을 다 찾아놓고 사용 ##
##########################################
# A Dynamic Programming based Python 
# Program for 0-1 Knapsack problem
# Returns the maximum value that can 
# be put in a knapsack of capacity W
def knapSack(W, wt, val, n):

    K = [[0 for x in range(W + 1)] for x 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]

    return K[n][W]

# Driver program to test above function
val = [60, 100, 120]
wt = [10, 20, 30]
W = 50
n = len(val)
print(knapSack(W, wt, val, n))
  
# This code is contributed by Bhavya Jain

####################################################
## 하향식(memoization): 재귀로 돌면서 필요한 값만 찾아 저장 ##
####################################################

# This is the memoization approach of 
# 0 / 1 Knapsack in Python in simple 
# we can say recursion + memoization = DP
  
# driver code
val = [60, 100, 120]
wt = [10, 20, 30]
W = 50
n = len(val)
  
# We initialize the matrix with -1 at first.
t = [[-1 for i in range(W + 1)] for j in range(n + 1)]
  
def knapsack(wt, val, W, n):    
  
    # base conditions
    if n == 0 or W == 0:
        return 0
    if t[n][W] != -1:
        return t[n][W]
  
    # choice diagram code
    if wt[n-1] <= W:
        t[n][W] = max(
val[n-1] + knapsack(
wt, val, W-wt[n-1], n-1), 
knapsack(wt, val, W, n-1))
        return t[n][W]
    elif wt[n-1] > W:
        t[n][W] = knapsack(wt, val, W, n-1)
        return t[n][W]
  
print(knapsack(wt, val, W, n))
  
# This code is contributed by Prosun Kumar Sarkar

...