def KnapSack(S, W, n):
# Base Case
if False:
pass
# Recursive Step
include = KnapSack(S, ?, n - 1) + S[0].b
not_include = KnapSack(S, ?, n - 1)
return None # Not done yet
def KnapSack(S, W, n):
# Base Case
if False:
pass
# Recursive Step
include = KnapSack(S, W - S[n - 1].w, n - 1) + S[0].b
not_include = KnapSack(S, W, n - 1)
return None # Not done yet
def KnapSack(S, W, n):
# Base Case
if False:
pass
# Recursive Step
include = KnapSack(S, W - S[n - 1].w, n - 1) + S[0].b
not_include = KnapSack(S, W, n - 1)
return max(include, not_include)
def KnapSack(S, W, n):
# Base Case
if W == 0 or n == 0:
return 0
if S[0].w > W:
return KnapSack(S, W, n - 1)
# Recursive Step
include = KnapSack(S, W - S[n - 1].w, n - 1) + S[0].b
not_include = KnapSack(S, W, n - 1)
return max(include, not_include)
memo = Matrix(W, n)
def KnapSack(S, W, n):
# Base Case
if W == 0 or n == 0:
return 0
if S[0].w > W:
return KnapSack(S, W, n - 1)
# Recursive Step
include = KnapSack(S, W - S[n - 1].w, n - 1) + S[0].b
not_include = KnapSack(S, W, n - 1)
return max(include, not_include)
memo = Matrix(W, n)
def KnapSack(S, W, n):
# Base Case
if W == 0 or n == 0:
return 0
if memo[W][n] != None:
return memo[W][n]
if S[0].w > W:
return KnapSack(S, W, n - 1)
# Recursive Step
include = KnapSack(S, W - S[n - 1].w, n - 1) + S[0].b
not_include = KnapSack(S, W, n - 1)
return max(include, not_include)
memo = Matrix(W, n)
def KnapSack(S, W, n):
# Base Case
if W == 0 or n == 0:
return 0
if memo[W][n] != None:
return memo[W][n]
if S[0].w > W:
return memo[W][n] := KnapSack(S, W, n - 1)
# Recursive Step
include = KnapSack(S, W - S[n - 1].w, n - 1) + S[0].b
not_include = KnapSack(S, W, n - 1)
return memo[W][n] := max(include, not_include)
def KnapSack(S, W, N):
memo = Matrix(W, n)
for n in range(1, N + 1):
for w in range(1, W + 1):
pass
def KnapSack(S, W, N):
memo = Matrix(W, n)
for n in range(1, N + 1):
for w in range(1, W + 1):
if S[n].w > W:
memo[w][n] = memo[W][n - 1]
else:
include = memo[w - S[n - 1].w][n - 1] + S[n - 1].b
not_include = memo[w][n - 1]
memo[w][n] = max(include, not_include)
return memo[N][W]
def Homework(e, h, n): # Not enough parameters!
# Base Case
if False:
pass
# Recursive Step
return None # Not done yet
def Homework(e, h, n, rested):
# Base Case
if n == 0:
return 0
# Recursive Step
nothing = Homework(e, h, n - 1, True)
easy = e[n - 1] + Homework(e, h, n - 1, False)
hard = h[n - 1] + Homework(e, h, n - 1, False) if rested else 0
return max(nothing, easy, hard) # Not done yet
def Homework(e, h, n):
memo = Matrix(n, 2)
for i in range(n):
for rested in range(2):
nothing = memo[i - 1][1]
easy = e[n - 1] + memo[i - 1][0]
hard = h[n - 1] + memo[n - 1][0] if rested else 0