Created
May 7, 2019 07:25
-
-
Save derekli66/016ea214d5ad40b27b37b480225384a9 to your computer and use it in GitHub Desktop.
This is another solution for knapsack problem. In this version, there is a 2-D array cache parameter with inout property in knapsack function. Use 2-D array to solve DP problem.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
func knapsack(_ weights: Array<Int>,_ values: Array<Int>,_ index: Int,_ remainingWeight: Int,_ cache: inout Array<Array<Int>>) -> Int { | |
if (index < 0) { return 0 } | |
if (cache[index][remainingWeight] != -1) { | |
return cache[index][remainingWeight] | |
} | |
var choosedValue: Int = 0 | |
if (remainingWeight >= weights[index]) { | |
// Choose | |
choosedValue = values[index] + knapsack(weights, values, index - 1, remainingWeight - weights[index], &cache) | |
} | |
// Not choose | |
let notChoosedValue = knapsack(weights, values, index - 1, remainingWeight, &cache) | |
cache[index][remainingWeight] = max(choosedValue, notChoosedValue) | |
return cache[index][remainingWeight] | |
} | |
let weights = [2, 5, 3, 1, 1] | |
let values = [10, 1, 2, 2, 1] | |
let weightLimit = 5 | |
var squareCache = Array<Array<Int>>() | |
for _ in 0..<weights.count { | |
squareCache.append(Array<Int>(repeating: -1, count: 6)) | |
} | |
let mostValue = knapsack(weights, values, weights.count - 1, weightLimit, &squareCache) | |
print("[Knapsack] The most value can be carried is \(mostValue)") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment